当TID响应kill系统调用时,有没有办法检测到PID真的死了,然后就像进程还活着一样。
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h> // gettid()
#include <sys/syscall.h>
static int gettid()
{
return syscall(SYS_gettid);
}
void *start(void *arg)
{
printf("thread start is %d\n", gettid());
(void)arg;
while (1)
{
sleep(1);
}
}
int
main(int argc, char *argv[])
{
pthread_t thread;
printf("Process is %d\n", getpid());
(void)pthread_create(&thread, nullptr, &start, nullptr);
while (1)
{
sleep(1);
// do_kill(thread);
}
}如果你编译这个
g++ -std=c++11 starttid.cpp -lpthread而执行它的pid比tid小1。如果你杀了tid
kill -0 <tid>tid将会响应,kill返回的错误将为0。我的问题是我有一个运行了很长时间的程序,并且没有被重写的选项。它跟踪它曾经启动过的所有进程。由于进程ID是环绕的,所以TID有时会替换原始PID。程序使用'kill(0,PID)‘检查进程是否正在运行。由于TID将捕获终止,因此这就像是进程仍然活着一样,尽管它已经退出很久了。
发布于 2016-11-14 13:46:10
为新线程TID重用的旧PID与为新进程PID重用的PID的情况没有什么不同。如果您的进程依赖于使用kill(0, pid)的轮询来查看进程何时退出,则这两种方法都是完全可能的-该方法具有固有的竞争条件。
您的进程应该使用waitpid()系统调用(可能与SIGCHLD处理程序配对)来跟踪其子进程的退出。
https://stackoverflow.com/questions/40558367
复制相似问题