c - 如何用 C 杀死管理线程?

标签 c pthreads kill sigkill

我有以下代码。构建应用程序是 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

}

顺便说一句:

linux 使用libuClibc-0.9.30.1.so 并根据这个问题How to kill all subprocess created with pthread_create after cancelling a thread?此 libc 使用 pthread 的 linux 线程实现,不使用带有 NPTL(“ native posix 线程库”)实现的 libc 因此管理线程将仅为这种 libc 情况创建。

最佳答案

我认为您遇到此问题是因为您根据 The Native POSIX Thread Library for Linux 使用 killall 终止了线程管理器来自 Redhat 的论文:

If the manager thread gets killed the remainder of the process is in a state which must be manually cleaned up.

还有Linux threading models compared :

A fatal signal is able to kill all the threads. The LinuxThreads design on this front has been consistent. Once a process receives a fatal signal, the thread manager kills all the other threads (processes) with the same signal.

这意味着如果你杀死线程管理器,它就没有机会杀死其他线程,所以你应该只使用 kill -p pid 而不是 来杀死主进程killall

我认为如果主进程正常存在,或者接收到信号,线程管理器最终也会在它完成杀死并等待其他线程时被杀死,但是,它也提到如果你调用 pthread_exit 所有其他进程在返回到 main 之前将被杀死:

If the main process calls pthread_exit(), the process is not terminated. The main thread goes to sleep, and it is the job of the manager thread to wake up the main thread when all other threads have been killed.

关于c - 如何用 C 杀死管理线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13305422/

相关文章:

c - 关于 printf 中的字符串

java - 精准消费时间解决方案

linux - 如何从 bash 从最新到最旧的进程杀死进程

process - 如何杀死cygwin中的进程?

c - 如何将自定义 Linux 信号从内核模块广播到所有正在运行的进程

c - C语言如何计算xls文件的MD5

c++ - pthread_join 错误,从线程创建线程

c - 在线程中使用不同的互斥锁

Android - 从另一个应用程序杀死应用程序(在 Root设备上)

c - "precompiler directive""preprocessor directive"