[英]Fork and exec several children in linux
我想从另一个分支并执行几个进程。 我的父母代码是
/*Daddy.c*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(void)
{
int status;
char *nChild;
for (int i=0; i<3;i++){
int pid = fork();
if (pid == 0)
{
sprintf(nChild, "%d", i);
printf("%d\n", i);
char *const arguments[]={nChild, NULL};
fflush(NULL);
execv("child",arguments);
printf("\nNo , you can't print!\n");
}else if (pid == -1){
printf("%d\n", getpid());
exit(0);
}
}
wait(&status);
printf("Dad %d went out!\n", getpid());
exit(0);
}
我的孩子过程是
/*child.c*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int args, char **argv){
if( args !=2){
printf("Child going away!\n");
exit(1);
}
printf("Child %s: %d going away stylishly!\n", argv[1], getpid());
exit(0);
}
当我不创建三个叉子时,我会创建一个孩子,做一些工作,然后退出孩子和父母。 但是,在这种情况下,有多个孩子似乎孩子永远不会执行。 由于使用了wait(&status)
这一行,我确实希望当第一个孩子退出时,父级也退出,但是,任何孩子都将打印任何消息。 先前的一些相关问题没有帮助。
您需要让父级等待所有子级进程完成。 如果不是,则假设1个等待的孩子完成,然后父母退出。 那另外两个孩子呢? 他们成为孤儿,因为他们的父母不等他们。
pid_t wpid;
int status = 0;
.
.
while ((wpid = wait(&status)) > 0); // the parent waits for all the child processes
这段代码完成了工作
/* daddy.c */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
int main(void)
{
int status=0;
char nChild[16];
pid_t wpid;
for (int i=0; i<3;i++){
sprintf(nChild, "%d", i);
int pid = fork();
if (pid == 0)
{
printf("%s\n", nChild);
char *const arguments[]={"child", nChild, NULL};
fflush(NULL);
execv("child",arguments);
printf("\nNo , you can't print!\n");
}else if (pid == -1){
printf("%d\n", getpid());
exit(0);
}
}
while ((wpid=wait(&status)) >0);
printf("Dad %d went out!\n", getpid());
exit(0);
}
正如@OnzOg在问题的评论中所说,分配nChild
是主要问题。 execv
还需要两次传递子名称,一个作为参数。 最后,为了改进代码,父进程需要等待所有进程完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.