gpt4 book ai didi

C: 用 scanf fork

转载 作者:太空狗 更新时间:2023-10-29 12:29:54 26 4
gpt4 key购买 nike

我试过这段代码

#include <stdio.h>
#include <sys/types.h>

int main(){

int x=3;
pid_t pid0=getpid();
pid_t pid1=0;

if(fork()==0){
pid1=getpid();
}

if(getpid()==pid1){
scanf("%d",&x);
printf("%d",x);
}

return 0;

}

scanf 指令被完全忽略。它只打印旧的 x,即 3。有人可以向我解释这里发生了什么吗?

最佳答案

这是对您的代码的主要小修改。它会检查 scanf() 是否正常工作,调用 getpid() 的频率会降低一些,并且会更仔细地报告一些事情。此外, parent 在退出之前等待 child 退出。

示例运行(我将程序命名为 fork7):

$ ./fork7 <<< ''
Parent (32976 - child 32977)
Child (32977)
Oops! 3
Child 32977: 0x0000
$ ./fork7 <<< 99
Parent (32978 - child 32979)
Child (32979)
Read: 99
Child 32979: 0x0000
$

代码(fork7.c):

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
int x = 3;
pid_t pid1;

if ((pid1 = fork()) == 0)
{
printf("Child (%d)\n", (int)getpid());
if (scanf("%d", &x) != 1)
printf("Oops! %d\n", x);
else
printf("Read: %d\n", x);
}
else
{
int corpse;
int status;
printf("Parent (%d - child %d)\n", (int)getpid(), (int)pid1);
while ((corpse = wait(&status)) > 0)
printf("Child %d: 0x%.4X\n", corpse, status);
}

return 0;
}

关于C: 用 scanf fork ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677682/

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