代码不打印父进程语句

时间:2018-02-11 19:30:52

标签: c process operating-system zombie-process

我正在运行以下代码:

// A C program to demonstrate Zombie Process. 
// Child becomes Zombie as parent is sleeping
// when child process exits.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
    // Fork returns process id
    // in parent process
    pid_t child_pid = fork();

    // Parent process 
    if (child_pid > 0)
        {printf("in parent process");
        sleep(50);
        }

    // Child process
    else       
        {   printf("in child process");
            exit(0);
        }

    return 0;
}

获得以下输出:

$main
in child process

我在这里运行代码:http://tpcg.io/6ZccnX

为什么声明“在父进程中”不能打印?

1 个答案:

答案 0 :(得分:1)

stdout通常不会刷新,直到出现新行 我已经测试了以下内容,两个选项都按预期工作:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
    // Fork returns process id
    // in parent process
    pid_t child_pid = fork();

    // Parent process 
    if (child_pid > 0)
    {
        /*option one: put '\n' at the end of the print to flush it */
        printf("in parent process\n");
        /*option two: flush all the available streams after print*/
//      printf("in parent process");
//      fflush(NULL);
        sleep(50);
    }

    // Child process
    else       
    {   printf("in child process");
        exit(0);
    }

    return 0;
}