日期:2014-05-16  浏览次数:20671 次

多进程编程fork()的问题
源程序是这样(编译环境在ubuntu13.10)
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>

int main(void)
{
pid_t child1, child2, child;

child1 = fork();
child2 = fork();

if(child1 == -1)
{
printf("Child1 fork error\n");
exit(1);
}
else if(child1 == 0)
{
printf("In child1:execute 'ls -l'\n");
     if(execlp("ls", "ls", "-l", NULL) < 0)
{
printf("Child1 execlp error\n");
}
}

if(child2 == -1)
{
printf("Child2 fork error\n");
exit(1);
}
else if(child2 == 0)
{
printf("In child2: sleep for 5 seconds and then exit\n");
sleep(5);
exit(0);
}
else
{
printf("In father process: \n");
child = waitpid(child1, NULL, 0);
if(child == child1)
{
printf("Get child1 exit code\n");
}
else
{
printf("Error occured!\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 exit code\n");
}
else
{
printf("Error occured!\n");
}
}
exit(0);
}

编译运行后为什么会产生两个“ls -l”
figure922@JeffyPC:~/homework/6.5.1$ ./multi_proc_wrong 
In father process: 
In child1:execute 'ls -l'
In child1:execute 'ls -l'

In child2: sleep for 5 seconds and then exit
总用量 32
总用量 32
-rwxr-xr-x 1 figure922 figure922 8820 12月  4 16:27 multi_proc
-rwxr-xr-x 1 figure922 figure922 8820 12月  4 16:27 multi_proc
-rw-r--r-- 1 figure922 figure922 1096 12月  4 16:24 multi_proc.c
-rwxr-xr-x 1 figure922 figure922 8826 12月  4 14:50 multi_proc_wrong
-rw-r--r-- 1 figure922 figure922 1100 12月  4 14:50 multi_proc_wrong.c
-rw-r--r-- 1 figure922 figure922 1096 12月  4 16:24 multi_proc.c
-rwxr-xr-x 1 figure922 figure922 8826 12月  4 14:50 multi_proc_wrong
-rw-r--r-- 1 figure922 figure922 1100 12月  4 14:50 multi_proc_wrong.c
Get child1 exit code
The child2 process has not exited!
The child2 process has not exited!
The child2 process has not exited!
The child2 process has not exited!
The child2 process has not exited!
Get child2 exit code