有人可以帮我理解以下代码的流程:
/* Child Process creation using fork() */
#include<stdio.h>
#include<stdlib.h>
main(){
int i=0;
pid_t chp1,chp2,chp3;
chp1=fork();
if(chp1<0){
fprintf(stderr,"Child creation failed\n");
exit(1);
}
else if(chp1==0){
printf("Inside Child Process1,process id is %d\n", getpid());
printf("Value of i in Child process1 is %d\n", i);
i=i++;
printf("Value of i in child process1 after increment is %d\n", i);
sleep(10);
}
else{
chp2=fork();
if(chp2==0){
sleep(30);
printf("Inside Child Process2,process id is %d\n", getpid());
printf("Value of i in Child process2 is %d\n", i);
i=i+2;
printf("Value of i in child process2 after increment is %d\n", i);
sleep(40);
}
else{
wait(chp2);
printf("Inside Parent Process, value of pid1=%d pid2=%d\n", chp1,chp2);
printf("Value of i in Parent process is %d\n", i);
i=i+5;
printf("Value of i in Parent process, after increment is %d\n", i);
wait(chp1);
}
}
printf("Common Section, Value of i=%d\n", i);
}
但是,在输出中,我可以看到
First Child1(chp1)将执行其printf部分并完成执行。
父进程正在执行其printf部分,然后等待child2。
Child2完成执行。
父完成执行。
[Rajim@rajim OS_Prog]$ ./a.out
Inside Child Process1,process id is 3291
Value of i in Child process1 is 0
Value of i in child process1 after increment is 1
Common Section, Value of i=1
Inside Parent Process, value of pid1=3291 pid2=3292 pid3=8605684
Value of i in Parent process is 0
Value of i in Parent process, after increment is 5
Inside Child Process2,process id is 3292
Value of i in Child process2 is 0
Value of i in child process2 after increment is 2
Common Section, Value of i=2
Common Section, Value of i=5
[Rajim@rajim OS_Prog]$
所以有人可以让我理解程序是如何流动的吗?
答案 0 :(得分:0)
您对wait()
的来电是错误的。 wait()不接受子参数的PID(以单参数形式),而是指向存储状态的int的指针。
将通话更改为:
else{
int status;
wait(&status);
...
请记住,wait
会从任何进程返回状态更改。如果您特别想等待某个流程,则应使用waitpid()
:
else{
int status;
waitpid(chp2, &status, 0);
此外,第一个孩子的行:
i=i++;
在C。
中调用undefined behaviour答案 1 :(得分:0)
为了匹配您的预期流量,在分配ch2之前需要wait
表示ch1。 ch1和父进程将并行运行,并且无法确定哪一个首先执行。因此,你的检查点必须让ch1退出后让父母继续执行。