gpt4 book ai didi

显示父子进程的C程序只显示子进程而不显示父进程

转载 作者:行者123 更新时间:2023-11-30 19:29:22 26 4
gpt4 key购买 nike

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

void main(){
int a,pid;
printf("Do you want to create a process? Press 1 for Yes ");
scanf("%d",&a);
if (a==1){
fork();}
else{printf("Fair enough");}

printf("This should print twice");

if (pid<0){printf(" Child process not created ");}

else if (pid>0){printf(" This is the parent process ");}

else{printf(" This is the child process ");}}

上面的代码显示以下输出

>Do you want to create a process? Press 1 for Yes 1
>This should print twice This is the child process This should print twice This is the child process

但是,我想要一个输出,当按下 1 时,会显示

>This should be printed twice
>This is child process
>This should be printed twice
>This is parent process

有人能指出我犯了什么逻辑错误吗?

最佳答案

您应该检查从 fork 获得的 pid,这是子/父代码的示例:

int main(){

int a, b;

pid_t pid;

a = 3;

b = 5;

pid = fork();

if (pid == -1)

{

printf("ERROR IN FORK MAIN\n");

}

if(pid == 0)

{

Add( a,b) ;/*a function for child to do*/

}

else
{

printf("Parent Done\n");

}
return 0;}

关于显示父子进程的C程序只显示子进程而不显示父进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52887970/

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