您的位置:首页 > 其它

如何在一个进程中生成两个子进程?

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: