Fork同时创建多个子进程方法
第一种方法:验证通过
特点:同时创建多个子进程,每个子进程可以执行不同的任务,程序
int main(void)
{
printf("before fork(), pid = %d\n", getpid());
pid_t p1 = fork();
if( p1 == 0 )
{
printf("in child 1, pid = %d\n", getpid());
return 0; //若此处没有return 0 p1 进程也会执行 pid_t p2=fork()语句
}
pid_t p2 = fork();
if( p2 == 0 )
{
printf("in child 2, pid = %d\n", getpid());
return 0; //子进程结束,跳回父进程
Printf("hello world\");//没有打印
}
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;
}
第二种方法:
特点:同时创建两个子进程,结构比较繁琐,程序可读性不好,不易扩展
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h> //这个头文件不能少,否则pid_t没有定义
main()
{
printf("This is parent process%d\n",getpid());
pid_t p1,p2;
if((p1=fork())==0)
{
printf("This is child_1 process%d\n",getpid());
}
Else
{
if((p2=fork())==0)
{
printf("This is child_2 process%d\n",getpid());
}
Else
{
wait(p1,NULL,0);
wait(p2,NULL,0);
printf("This is parent process%d\n",getpid());
}
}
}
第三种方法:for
特点:其实每次循环只是创建了单个进程,并没有同时创建多个进程
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
main()
{
printf("This
pid_t
int
for(i=0;i<=2;i++)
{
if((p1=fork())==0)
{
printf("This
return
}
wait(p1,NULL,0);
printf("This
}
}
注意:标注的
无
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
main()
{
printf("This
pid_t
int
for(i=0;i<=2;i++)
{
if((p1=fork())==0)
{
printf("This
//return
}
wait(p1,NULL,0);
printf("This
}
}
结论:父进程会生成
正确的使用Linux中的用fork()由一个父进程创建同时多个子进程
void
{
}
是大哥大法官
void
{
}
void
{
}