简体   繁体   English

多个前叉语句

[英]Multiple Fork Statements

This code creates 3 processes in addition to the the original one. 除了原始代码外,此代码还创建了3个过程。 So in total 4 processes exist. 因此,总共存在4个过程。 As far as i know, this code should print 8 statements. 据我所知,此代码应打印8条语句。 However the result is just 4 statements. 但是结果只有4条语句。 What am i missing here? 我在这里想念什么?

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

// error checking is omitted 

int main(int argc, char const *argv[])
{
    pid_t pid, pid2;

    fflush(stdout);// used to clear buffers before forking
    pid = fork();
    fflush(stdout);
    pid2 = fork();

    if(pid == 0) {
        printf("%d is the first generation child from first fork\n", getpid());
    }

    else if(pid > 0) {
        printf("%d is the original process\n", getpid());
        wait();
    }

    else if(pid2 == 0) {
        printf("%d is the 2nd generation child from the second fork by the first generation child  \n", getpid());
    }

    else if(pid2 > 0) {
        printf("%d is the first generation younger child from the 2nd fork by the original\n", getpid() );
        wait();
    }

    return 0;
}

output 输出

4014 is the original process 4016 is the original process 4015 is the first generation child from first fork 4017 is the first generation child from first fork 4014是原始进程4016是原始进程4015是来自第一个fork的第一代子代4017是来自第一个fork的第一代子代

It's because of else if, each process can only print one line and 4 process means 4 lines. 这是因为,如果每个进程只能打印一行并且4个进程表示4行。

You should replace: 您应该替换:

else if(pid2 == 0) {

By: 通过:

 if(pid2 == 0) {

Both tests on pid and pid2 must be done to print 2 lines per process. 必须对pid和pid2进行两项测试,以便每个进程打印2行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM