【问题标题】:How to kill the management thread with C?如何用C杀死管理线程?
【发布时间】:2012-11-09 09:37:01
【问题描述】:

我有以下代码。构建应用程序是 myprogram。

如果我启动 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

}

顺便说一句:

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 thread library”)实现的libc 所以只会为这种libc创建管理线程。

【问题讨论】:

    标签: c pthreads kill sigkill


    【解决方案1】:

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

    如果管理器线程被杀死,则进程的其余部分处于 必须手动清理的状态。

    还有Linux threading models compared:

    致命信号能够杀死所有线程。这方面的 LinuxThreads 设计一直是一致的。 一旦一个进程收到一个 致命信号,线程管理器杀死所有其他线程 (进程)具有相同的信号。

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

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

    如果主进程调用pthread_exit(),进程不在 终止。主线程进入睡眠状态,这是 当所有其他线程都有时,管理器线程唤醒主线程 被杀了。

    【讨论】:

    • 有没有办法用 C 杀死管理器线程?在我的程序结束时。
    • 当我的程序从外部命令收到killall 或kill -p 时,有没有办法执行pthread_exit()?
    • 是的,我认为您可以从信号处理程序调用pthread_exit(),但 killall 不会仅向主进程发送信号,而是将其发送到包括线程管理器在内的所有进程,因此它可以在主进程之前被杀死,你应该只使用 kill @MohamedKALLEL
    • 你应该尝试kill -p pid使用主进程的pid,如果不会杀死所有进程,但我很确定它会,然后使用pthread_exit()
    • 参考stackoverflow.com/questions/13309415/…了解如何处理来自C代码的killall信号
    猜你喜欢
    • 2011-06-29
    • 2011-02-13
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2017-11-11
    相关资源
    最近更新 更多