c - 此代码是否会导致从父进程成功创建两个子进程?

标签 c fork

这是我的 C 代码,用于从父进程创建两个子进程。 这样能创建成功吗?我当前的输出是:

You are in parent process whose id is 29509
you are in child process 1 and your parent id is 29509
You are in parent process whose id is 29511
you are in child process 2 and your parent id is 29509

为什么在我输出的第三行中父 ID 不同??

    #include<stdio.h>
    #include<unistd.h>
    int main(){
            pid_t child1,child2;
            int c,d,e;
            child1=fork();
            if(child1==0){
                    c=getppid();
                    printf("you are in child process 1 and your parent id is %d\n",c);

            }
            else{
                    child2=fork();
                    e=getpid();
                    printf("You are in parent process whose id is %d\n",e);
            }
            if(child2==0){
                    d=getppid();
                    printf("you are in child process 2 and your parent id is %d\n",d);
            }
    }

输出是

You are in parent process whose id is 29509
you are in child process 1 and your parent id is 29509
You are in parent process whose id is 29511
you are in child process 2 and your parent id is 29509 

最佳答案

在您的第二个fork 之后,父进程和第二个子进程都执行“父进程”printf

关于c - 此代码是否会导致从父进程成功创建两个子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21382527/

相关文章:

c - 操作系统(Unix)中的新进程创建

python - 使用子流程找出流程何时结束

python - 是否可以监视 forked linux 进程的写时复制? (特别是 python )

c - 为指针赋值导致硬故障

c - OSX 上的 getsockopt 返回错误值?

c - 如何向套接字发送信号?

c - C 中的 Pthread_cond_wait

c - 为什么 malloc() 可以互换调用 mmap() 和 brk()?

c - GNU C 使用管道的多进程处理

node.js - node.js ChildProcess.fork() 中的字符编码