[英]C - Waiting for one child to terminate
I am creating multiple child processes in a loop. 我正在循环中创建多个子进程。 Each child will do it's thing and anyone of them can end first. 每个孩子都会做这件事,任何人都可以先结束。 (Not sure if relevant but: Each child also has a grandchild) (不确定是否相关,但:每个孩子都有一个孙子)
How do I wait for any child process to terminate and stop the others when one has finished ? 如何等待子进程终止并停止其他子进程?
for(i=0; i<numberOfChildren; i++)
{
pid = fork();
if(pid < 0)
{
fprintf(stderr, "Error: fork Failed\n");
return EXIT_FAILURE;
}
/* Child Process */
if(pid == 0)
{
/* Do your thing */
}
/* Parent process */
else
{
childrenPid[i]=pid;
}
}
You can suspend the parent until one of its children terminates with the wait
call and then kill
the remaining children: 您可以暂停父级,直到其子级中的一个终止wait
调用,然后kill
其余的子级:
#include <sys/types.h>
#include <wait.h>
int status;
childpid = wait(&status)
Then, if you have stored the process ID of all children you created in an array, you can kill the remaining children: 然后,如果您已将在数组中创建的所有子进程的进程ID存储在其中,则可以杀死其余的子进程:
#include <sys/types.h>
#include <signal.h>
for(i = 0; i < nchildren; i++)
if (children[i] != childpid)
kill(children[i],SIGKILL)
where nchildren
is an integer count of the number of children created and children
is the array of pid_t of the children created. 其中nchildren
是创建的子nchildren
的整数,而children
是创建的children
的pid_t数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.