我有以下代码。构建应用程序是myprogram。如何用C杀死管理线程?
如果我启动myprogram,然后killall myprogram,之后立即启动myprogram,然后myprogram崩溃。
崩溃原因是由于第一次启动时创建的管理线程在第二次启动之前未正确清除。
因此在第二次启动时myprogram尝试使用pthread创建线程,旧线程管理未被删除,因此导致崩溃。
有没有办法在第一次启动结束时或第二次启动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
并根据这个问题How to kill all subprocess created with pthread_create after cancelling a thread?这个libc中使用Linux的线程执行的pthread
,不与NPTL( “本地POSIX线程库”)实施 使用的libc所以管理线程将只为这种libc的情况创建。
有没有办法用C来杀死管理线程?在我的节目结束时。 – MOHAMED
@MohamedKALLEL检查更新。 – iabdalkader
当我的程序从外部命令收到'killall'或'kill -p'时,有没有办法执行'pthread_exit()'? – MOHAMED