我必须编写一个程序来分叉3个子进程。
父进程只显示一次自己的PID信息,然后等待其子进程死掉。
在所有子进程终止后,主进程显示“主进程终止”,然后退出。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main( int argc, char *argv[], char *env[] )
{
pid_t my_pid, parent_pid, child_pid;
int status;
/* get and print my pid and my parent's pid. */
my_pid = getpid(); parent_pid = getppid();
printf("\n Parent: my pid is %d\n\n", my_pid);
printf("Parent: my parent's pid is %d\n\n", parent_pid);
/* print error message if fork() fails */
if((child_pid = fork()) < 0 )
{
perror("fork failure");
exit(1);
}
/* fork() == 0 for child process */
if(child_pid == 0)
{
execl("/bin/date", "date", 0, 0);
printf("This print is after execl() and should not have been executed if execl were successful! \n\n");
_exit(1);
}
/*
* parent process
*/
else
{
printf("\nParent: I created a child process.\n\n");
printf("Parent: my child's pid is: %d\n\n", child_pid);
wait(&status); /* can use wait(NULL) since exit status
from child is not used. */
printf("\n Parent: my child is dead. I am going to leave.\n \n ");
}
return 0;
}
答案 0 :(得分:-1)
对不起,我想写评论,但我没有足够的声誉。
如果您想首先显示父pid。然后您可以在getpid()
之前使用fork()
,那么您可以使用waitpid
进行收割。可能需要一个循环来收获所有这三个孩子