请教一些有关linux下c语言的函数fork()
#include<stdio.h>#include<unistd.h>#include<sys/types.h>intmain(){pid_tchild=0;inti,n...
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t child = 0;
int i,n;
printf("please input num:");
scanf("%d",&n);
for(i = 0; i<n; i++)
{
printf("%d befor %d\n",getpid(),i);
if((child = fork()) <= 0) break;
else printf("%d:%d\n",getpid(),i);
}
printf("mypid is %d,my i is %d,my father is %d,my child is %d\n",getpid(),i,getppid(),child);
}
实验数据:输入5。
please input num:5
11077 befor 0
mypid is 11081,my i is 0,my father is 11077,my child is 0
11077:0 if((child = fork()) <= 0) break;
11077 befor 1
mypid is 11082,my i is 1,my father is 11077,my child is 0
11077:1
11077 befor 2
mypid is 11083,my i is 2,my father is 11077,my child is 0
11077:2
11077 befor 3
mypid is 11084,my i is 3,my father is 11077,my child is 0
11077:3
11077 befor 4
mypid is 11085,my i is 4,my father is 11077,my child is 0
11077:4
mypid is 11077,my i is 5,my father is 10901,my child is 11085
疑问:为什么输出befor那一行的都是父进程,按我的理解,到 if((child = fork()) <= 0) break;时才应该退出,即子进程也应当显示 printf("%d befor %d\n",getpid(),i);这一行。但事实显示,没有,这是为什么呢? 展开
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t child = 0;
int i,n;
printf("please input num:");
scanf("%d",&n);
for(i = 0; i<n; i++)
{
printf("%d befor %d\n",getpid(),i);
if((child = fork()) <= 0) break;
else printf("%d:%d\n",getpid(),i);
}
printf("mypid is %d,my i is %d,my father is %d,my child is %d\n",getpid(),i,getppid(),child);
}
实验数据:输入5。
please input num:5
11077 befor 0
mypid is 11081,my i is 0,my father is 11077,my child is 0
11077:0 if((child = fork()) <= 0) break;
11077 befor 1
mypid is 11082,my i is 1,my father is 11077,my child is 0
11077:1
11077 befor 2
mypid is 11083,my i is 2,my father is 11077,my child is 0
11077:2
11077 befor 3
mypid is 11084,my i is 3,my father is 11077,my child is 0
11077:3
11077 befor 4
mypid is 11085,my i is 4,my father is 11077,my child is 0
11077:4
mypid is 11077,my i is 5,my father is 10901,my child is 11085
疑问:为什么输出befor那一行的都是父进程,按我的理解,到 if((child = fork()) <= 0) break;时才应该退出,即子进程也应当显示 printf("%d befor %d\n",getpid(),i);这一行。但事实显示,没有,这是为什么呢? 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询