简体   繁体   English

在C ++中,fork and kill不杀死所有子进程

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

I have below code which executes a binary in child process, wait for 1 sec and if it's not done then kill it. 我下面的代码在子进程中执行二进制文件,等待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");
     }

But it's not killing completely , I see below ps output after running my program 3 times (it created 3 version.out's), and "sh" appear as zombie... 但这并没有完全杀死我,我的程序运行了3次(创建了3个version.out)后,在ps输出下面看到了,“ 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
# 

Or, is there a way to run the command with timeout in busybox Linux? 或者,是否有一种方法可以在busybox Linux中使用超时运行命令?
Something like: 就像是:

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

There is no timeout in my busybox version, is there an alternative? 我的busybox版本没有超时,还有其他选择吗?

You are creating a shell (the child) which in turn runs "version.out" (the grandchild). 您正在创建一个外壳程序(子级),该外壳程序又运行“ version.out”(孙级)。

You kill the child thereby making it a zombie and orphaning the grandchild. 您杀死了孩子,从而使其成为僵尸并孤立了孙子。 You can collect the child by calling wait a second time (it error-ed out the first time or you would never have called kill ) but you still won't accomplish the goal of killing the grandchild from the parent. 您可以通过再次调用wait来收集孩子(第一次出错,否则您永远不会调用kill ),但是您仍然无法实现杀死父母的孙子的目标。

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

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