简体   繁体   English

无法检测子进程是否已被杀死

[英]Cannot detect if child process has been killed

I been reading a countless time on stackoverflow that to determine if a process is running, one should use kill(pid,0) but I cant make it work 我一直在阅读关于计算器溢出的无数时间,以确定一个进程是否正在运行,应该使用kill(pid,0),但我无法使其正常工作

here is my code, , it cannot detect when the child process has been killed and I dont understand why 这是我的代码,它无法检测子进程何时被杀死,我也不明白为什么

(sorry for the ident, but hte code escaping on stackoverflow is just a pain for long pieces of codes) (很抱歉,但是对于长代码来说,在堆栈溢出时转义的代码只是一个痛苦)

#include <sys/signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

int main()
{
int pid = fork();

if (pid < 0)
{
    printf("Forking failed\n");
} 
else if (pid == 0) // child process
{ 
    do
    {
        printf("child process\n");  
        sleep(1);
    }while(1);
    //execvp("ls", NULL); //launches the application
} 
else //parent process
{ 
    printf("parent process\n");
    for(int i=0;i<10;i++)
    {
        if(i==5)
            kill(pid,SIGTERM); //kills the child process
        if(kill(pid, 0) == 0)
            printf("process child %d is runnig\n",pid);
        else if(kill(pid, 0) == -1)
        {
            switch(errno)
            {
                case ESRCH: printf("process child %d is not runnig\n",pid); break;
                case EPERM: printf("process child %d cannot be killed\n",pid); break;
                default: printf("%s\n",strerror(errno));    break;
            }
        }

        sleep(1); 
    }

} 
}

here is the output 这是输出

parent process
process child 1918 is runnig
child process
process child 1918 is runnig
child process
process child 1918 is runnig
child process
process child 1918 is runnig
child process
process child 1918 is runnig
child process
process child 1918 is runnig
process child 1918 is runnig
process child 1918 is runnig
process child 1918 is runnig
process child 1918 is runnig

Until the killed child process gets reaped by wait() , its PID is still valid, and kill(pid, 0); 在被wait()杀死被杀死的子进程之前,其PID仍然有效,并且kill(pid, 0); will succeed, since the PID exists. 由于PID存在,将成功。 Your code attempts to kill() the child process, but fails to wait() for it. 您的代码尝试kill()子进程,但没有wait()它。

Note that even in the best case, kill(pid, 0); 注意即使在最好的情况下, kill(pid, 0); is not reliable. 不可靠。 With only 32766 different PIDs, it doesn't take long before process IDs get recycled. 仅使用32766个不同的PID,很快就可以回收进程ID。

alright I finaly figured it out 好吧,我最终想通了

kill(pid,SIGTERM); //kills the child process
do
    {
       pid = waitpid(-1, NULL, WNOHANG);
   if(pid == 0)
      sleep(1);
}while(pid<=0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM