|
照着参考书写了一个多进程的简单程序,编译执行后发现子进程child1竟然被创建了两次。不太明白为什么?而且我把child1子进程中的execlp函数调用去掉以后,child2好像也被创建了两次,好像一次是父进程创建的,一次是child1进程创建的。不太明白linux下进程创建和执行的过程。望各位高手指点。
谢谢了阿。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
printf("the parent pid is %d\n",getpid());
pid_t child1,child2,child;
child1 = fork();
child2 = fork();
if( child1 == -1 ){
perror("child1 fork");
exit(1);
}
else if( child1 == 0 ){
printf("the child1 pid is %d\n",getpid());
printf("In child1: execute 'ls -l'\n");
if(execlp("ls","ls","-l",NULL)<0)
perror("child1 execlp");
}
if( child2 == -1 ){
perror("child2 fork");
exit(1);
}
else if( child2 == 0 ){
printf("the child2 pid is %d\n",getpid());
printf("In child2: sleep for 5 seconds and then exit\n");
sleep(5);
exit(0);
}
else{
printf("the parent of the child2 pid is %d\n",getpid());
printf("In father process:\n");
do{
child = waitpid( child2, NULL, WNOHANG );
if( child ==0 ){
printf("The child2 process has not exited!\n");
sleep(1);
}
}while( child == 0 );
if( child == child2 )
printf("Get child2\n");
else
printf("Error occured!\n");
}
} |
|