【问题标题】:Code not printing parent process statements代码不打印父进程语句
【发布时间】:2018-02-11 19:30:51
【问题描述】:

我正在运行以下代码:

// 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

为什么“在父进程中”语句不打印?

【问题讨论】:

  • 因为你sleep(50);。单位是秒,时间长了。改成sleep(1);一切正常。
  • 您可能想使用printf("in parent process\n");,或printf("in parent process"); fflush(stdout);
  • 标准输出的输出通常被缓冲,直到出现换行符。将换行符放在您想要查看的输出的末尾。 (即便如此,如果您将输出通过管道传输到另一个程序或重定向到文件,仅换行符不一定会强制输出;您可能还需要使用 fflush(stdout) — 或者相反,换行符是个好主意一般)。

标签: c process operating-system zombie-process


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2014-10-04
    • 2021-12-25
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多