在C++中,fork和kill并没有杀死所有的子进程

In C++, fork and kill not killing all the child processes

本文关键字:子进程 并没有 kill C++ fork      更新时间:2023-10-16

我有下面的代码,它在子进程中执行二进制,等待1秒,如果没有完成,就杀死它。

     pid_t pid;
     pid=fork();
     if (pid == 0)
     {
         //In child
         execl("/bin/sh", "sh", "-c", "/opt/qcom/bin/version.out > /tmp/version", (char *)NULL);
         exit(0);
     }
     else
     {
         // In parent, wait for 1 second
         sleep(1);
         int status;
         if (waitpid(pid, &status, WNOHANG) != pid)
         {
             //kill(pid, SIGTERM); //--> tried this too
             kill(pid, SIGKILL);
         }
         fsmverDir("/tmp/version");
         system("rm /tmp/version");
     }

但它并没有完全杀死,我在运行我的程序3次后看到下面的ps输出(它创建了3个版本.out),"sh"看起来像僵尸。。。

# ps | grep "version.out|sh"
2012 root         0 Z    [sh]
2013 root     13236 S    /opt/qcom/bin/version.out
2058 root         0 Z    [sh]
2059 root     13236 S    /opt/qcom/bin/version.out
2092 root         0 Z    [sh]
2093 root     13236 S    /opt/qcom/bin/version.out
2100 root      2360 S    grep version.out|sh
# 

或者,有没有一种方法可以在busybox Linux中超时运行命令
类似于:

execlp("timeout","timeout","1","sh","-c","/opt/qcom/bin/version.out > /tmp/version",NULL);

在我的busybox版本中没有超时,有其他选择吗?

您正在创建一个shell(子shell),它反过来运行"version.out"(孙shell)。

你杀死了孩子,从而使其成为僵尸,并使孙子成为孤儿。你可以通过第二次调用wait来收集孩子(第一次它出错了,否则你永远不会调用kill),但你仍然无法实现从父母那里杀死孙子的目标。