How to kill a control thread using C?

I have the following code. build application is myprogram.

If I run myprogram and then killall myprogram and immediately after that run myprogram again, then myprogram crashes.

The reason for the failure is that the control thread created by the first run was not properly cleaned until the second run.

therefore, in the second run, when myprogram tries to create a thread with pthread, and the old thread control has not yet been removed, so it causes a crash.

Is there a way to kill the control flow at the end of my first run or at the beginning of my second run using C ?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_t test_thread;

void *thread_test_run (void *v)
{
    int i=1;
    while(1)
    {
       printf("into thread %d\r\n",i);
       i++; 
       sleep(1);
    }
    return NULL
}

int main()
{
    // ps aux | grep myprogram  ---> show 1 myprogram (1 for the main application)

    pthread_create(&test_thread, NULL, &thread_test_run, NULL);

    // ps aux | grep myprogram  ---> show 3 myprogram
    // (1st for the main application)
    // (2nd for the management thread. thread which manage all created thread)
    // (3rd for the created thread)

    sleep (20);  


    pthread_cancel(test_thread);

    // ps aux | grep myprogram  ---> show 2 myprogram and
    // (1st for the main application)
    // (2nd for the management thread. thread which manage all created thread)

    sleep(100);
    // in this period (before the finish of myprogram)
    // I execute killall to kill myprogram 
    // and then immediately I re-launch myprogram and then the program crash
    // because the management thread is not immediately killed

}

BTW:

linux libuClibc-0.9.30.1.so , pthread_create ? libc linux- pthread libc NPTL ( "Native posix thread library" ) libc.

+3
1

, , killall The Native POSIX Thread Library Linux Redhat:

, .

Linux :

. LinuxThreads . , () .

, , , , kill -p pid not killall

, , , , , pthread_exit , :

pthread_exit(), , . , , , .

+5

Source: https://habr.com/ru/post/1659479/


All Articles