特点:同时创建多个子进程,每个子进程可以执行不同的任务,程序可读性较好,便于分析,易扩展为多个子进程
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t p1,p2;
printf("before fork(),pid=%d\n",getpid());
p1=fork();
if(p1==0)
{
printf("in child 1, pid = %d\n", getpid());
return 0;
}
p2 = fork();
if( p2 == 0 )
{
printf("in child 2, pid = %d\n", getpid());
return 0; //程序结束不再执行
printf("Hello world\n");
}
/*int st1, st2;
waitpid(p1, &st1, 0);
waitpid(p2, &st2, 0);
printf("in parent, child 1 pid = %d\n", p1);
printf("in parent, child 2 pid = %d\n", p2);
printf("in parent, pid = %d\n", getpid());
printf("in parent, child 1 exited with %d\n", st1);
printf("in parent, child 2 exited with %d\n", st2);*/
return 0;
}
执行结果:
before fork(),pid=23