#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
pid_t child1, child2, father;
//child2=fork();
child1=fork();
if(child1 < 0)
{
printf("child1 is error\n");
exit(1);
}
else if(child1 == 0)
{
printf("child1 execute ls-l\n");
execlp("/bin/ls","ls","-l","/home/zzd/class",(char *)NULL);
exit(0);
}
else
{
child2=fork(); //第2个fork一定要写在这,也就是父进程里面创建一个子进程。放在前面child1会运行2次,也就是实际上变成了4个进程。
if(child2 < 0)
{
printf("child2 is error\n");
exit(0);
}
else if(child2 == 0)
{
printf("child2 sleep for 5 seconds\n");
sleep(5);
exit(0);
}
//wait(NULL);
father=waitpid(child1,NULL,0);
if(father=child1)
printf("child1 success\n");
else
printf("error");
do
{
father=waitpid(child2,NULL,WNOHANG);
}while(father==0);
if(father=child2)
printf("child2 success\n");
}
return 0;
}
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
pid_t child1, child2, father;
//child2=fork();
child1=fork();
if(child1 < 0)
{
printf("child1 is error\n");
exit(1);
}
else if(child1 == 0)
{
printf("child1 execute ls-l\n");
execlp("/bin/ls","ls","-l","/home/zzd/class",(char *)NULL);
exit(0);
}
else
{
child2=fork(); //第2个fork一定要写在这,也就是父进程里面创建一个子进程。放在前面child1会运行2次,也就是实际上变成了4个进程。
if(child2 < 0)
{
printf("child2 is error\n");
exit(0);
}
else if(child2 == 0)
{
printf("child2 sleep for 5 seconds\n");
sleep(5);
exit(0);
}
//wait(NULL);
father=waitpid(child1,NULL,0);
if(father=child1)
printf("child1 success\n");
else
printf("error");
do
{
father=waitpid(child2,NULL,WNOHANG);
}while(father==0);
if(father=child2)
printf("child2 success\n");
}
return 0;
}