linux中fork同时创建多个子进程的方法

来源:互联网 发布:mysql innodb重建索引 编辑:程序博客网 时间:2024/06/10 14:59
第一种方法:验证通过

特点:同时创建多个子进程,每个子进程可以执行不同的任务,程序 可读性较好,便于分析,易扩展为多个子进程

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()); //while(1);//进入子进程1的处理函数return 0; //若此处没有return 0 p1 进程也会执行 pid_t p2=fork()语句} pid_t p2 = fork(); if( p2 == 0 ) { printf("in child 2, pid = %d\n", getpid()); //while(1);//进入子进程2的处理函数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; } 

第二种方法:for 循环方法
特点:其实每次循环只是创建了单个进程,并没有同时创建多个进程 

#include<stdio.h> #include<unistd.h> #include<sys/types.h> int main() {printf("This is parent process%d\n",getpid()); pid_t p1,p2; int i; for(i=0;i<=2;i++){ if((p1=fork())==0){ printf("This is child_1 process%d\n",getpid()); return 0;//这个地方非常关键 } wait(p1,NULL,0); //父进程等待p1子进程执行后才能继续fork其他子进程printf("This is parent process%d\n",getpid()); }} //注意:标注的 return 0 对程序结果影响很大
正确的使用Linux中的用fork()由一个父进程创建同时多个子进程 的格式如下:

int status,i;for (i = 0; i < 10; i++){status = fork();if (status == 0 || status == -1) break;//每次循环时,如果发现是子进程就直接从创建子进程的循环中跳出来,不让你进入循环,这样就保证了每次只有父进程来做循环创建子进程的工作}if (status == -1){//error}else if (status == 0) //每个子进程都会执行的代码{//child's sub processwhile(1);}else{//parent processwhile(1);}

fock 的意思是复制进程, 就是把当前的程序再加载一次, 不同之处在,加载后,所有的状态和当前进程是一样的(包括变量)。 fock 不象线程需提供一个函数做为入口, fock后,新进程的入口就在 fock的下一条语句。返回:子进程中为0,父进程中为子进程I D,出错为-1



原创粉丝点击