gpt4 book ai didi

c - 使用 wait()-sleep() 函数调用的父子关系

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:54 25 4
gpt4 key购买 nike

谁能帮我理解下面代码的流程:

    /* 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);
}

--->输出的行为应该是这样的:

  1. 第一个 Child1(chp1) 将执行其 printf 部分并完成其执行。
  2. 然后 Child2(chp2) 将执行其 printf 部分并完成其执行。
  3. 最后,父进程会执行它的printf部分(因为它的printf部分之前有wait(chp2),所以它会等待child2的执行)并结束它的执行。

但是,在输出中,我可以看到

  1. 第一个 Child1(chp1) 将执行其 printf 部分并完成其执行。

  2. 父进程正在执行它的 printf 部分,然后等待 child2。

  3. Child2 完成执行。

  4. 父级完成其执行。

输出如下:

[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]$

那么有人可以让我了解程序的流程吗?

最佳答案

您对 wait() 的调用是错误的。 wait()不接受子参数的 PID(以单个参数形式),而是一个指向 int 的指针来存储状态。

将调用更改为:

   else{
int status;
wait(&status);
...

请记住,wait 会在任何 进程的状态更改时返回。如果你特别想等待一个进程,你应该使用 waitpid():

 else{
int status;
waitpid(chp2, &status, 0);

此外,第一个 child 中的行:

i=i++;

调用 undefined behaviour在 C 中。

关于c - 使用 wait()-sleep() 函数调用的父子关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24314909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com