显示父进程和子进程的C程序仅显示子进程而不是父进程

时间:2018-10-19 07:49:37

标签: c operating-system

#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

谁能指出我犯了什么逻辑错误?

1 个答案:

答案 0 :(得分:0)

您应该检查从叉子获得的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;}