如何在一个进程中生成两个子进程?
2010-11-18 00:05
302 查看
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main(void) { pid_t pid1; pid_t pid2; pid1=fork(); /*这里定义第一个子进程*/ pid2=fork(); /*这里定义第二个子进程*/ if(pid1<0 || pid2<0) printf("Error.fock call fail/n"); //else if(pid1!=0 && pid2!=0) //print("This is the parent process/n"); else if(pid1 == 0) /*当第一个子进程运行时*/ printf("This is the NO.1 child process/n"); else if(pid2 == 0) /*当第二个子进程运行时*/ printf("This is the NO.2 child process/n"); else printf("This is the parent process/n"); printf("Fork end./n/n"); exit(0); }
运行结果为:
-----------------------------
This is the NO.1 child process
Fork end.
This is the NO.1 child process
Fork end.
This is the NO.2 child process
Fork end.
This is the parent process
Fork end.
---------------------
以上运行结果可以看出,似乎子进程1运行了2次,其实不然。首先,在运行pid2=fork()前,已有主进程和子进程1存在。在主进程中pid1不为0,所以,当主进程再次生成子进程2后,能够顺利显示“This is the parent process.Fork end.”和“This is the NO.2 child process.Fork end.”;然而,在子进程1中,由于pid为1,所以即使它也生成了子进程2,但2个进程都只会运行到19行。原本应该运行进入行的子进程2却应为pid1==0在pid2==0之前,而无法进入,最终导致两次显示NO.1 child process。
代码可修改如下:
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main(void) { pid_t pid1; pid_t pid2; pid1=fork(); /*这里定义第一个子进程*/ if(pid1<0) printf("Error.NO.1 fock call fail/n"); else if(pid1 == 0) printf("This is the NO.1 child process/n"); else { pid2=fork(); /*第二个子进程在判断为父进程后再创建.这样可以避免了在第一进程中再次创建下一级的一个子进程*/ if(pid2<0) printf("Error.NO.2 fock call fail/n"); else if(pid2 == 0) printf("This is the NO.2 child process/n"); else printf("This is the parent process/n"); } printf("Fork end./n/n"); exit(0); }
相关文章推荐
- fork()调用的一个趣题--fork函数能生成几个子进程???
- fork()调用的一个趣题--fork函数能生成几个子进程???
- 如何用一个父进程创建多个子进程?
- 使用python的os.fork()为一个主进程生成多个子进程
- 用fork函数,由一个父进程生成两个子进程
- 如何通过一个毫不相关的进程去控制另一进程窗口中数据
- Linux 如何查看一个进程的堆栈
- 在JSP中动态生成随机验证码,登录时后台校验验证码,以及如何避免同一个验证码被重复提交爆破密码
- C# 如何生成一个时间戳
- 我在delphi中用shellExecute启动了一个程序(ftp);然后想做一个等待,只到ftp进程结束,再继续下面的操作,请问如何监控这个进程是否已结束?
- sql 2005 中如何自动生成不重复的,长度相同字符串作为一个数据表的id
- 如何将一个进程(线程)绑定到一个固定的CPU核上?
- 如何写一个简单的守护(精灵)进程原型
- 如何开发一个java开源框架-----Jvn框架之实现自动生成在线文档(第七讲)
- 如何在Windows XP以上的版本中得知一个进程所使用的端口
- 现在有一个进程挂起了,如何用工具查出原因
- 如何使用Cocos2D 2.X生成一个简单的iPhone游戏 (2/8)
- 如何生成一个可以使用百度地图的发布key值
- 如何控制JAVA中一个类只能生成一个对象?
- 如何将所有的进程运行在一个指定的CPU上