【问题标题】:Fork Issue - After executing fork(), commands before fork are also running twiceFork 问题 - 执行 fork() 后,fork 之前的命令也运行了两次
【发布时间】:2014-09-21 05:08:17
【问题描述】:

这是输出 ---

家长:我的 pid 是 4525 父母:我父母的pid是3350 父母开始 - 4525 3350 分叉前 分叉前 儿童 4526 4525 在父母 ---父母端---

当我尝试执行以下代码时---

void main(int argc, char *argv[])
{
    int status;
    pid_t my_pid, parent_pid,child_pid;

    my_pid = getpid();
    parent_pid = getppid();
    printf("\nParent: my pid is %d", my_pid);
    printf("\nParent: my parent's pid is %d", parent_pid);
    printf("\nparant started- %d    %d",my_pid,parent_pid);
    printf("\nBefore Fork");

    if((child_pid = fork()) < 0 )
    {
        perror("fork failure");
        exit(1);
    }

    if(child_pid == 0)
    {
        printf("\n Child %d %d\n",getpid(),getppid());

    }
    else
    {
        printf("\nIn parent");
        wait(&status);
        printf("\n---Parent End---\n");
    }

}

为什么 Before Fork 会打印两次?谢谢

【问题讨论】:

  • ...顺便说一句,main() 返回int

标签: c linux fork


【解决方案1】:

这是因为您没有在fork() 之前刷新输出缓冲区。改为:

printf("\nBefore Fork\n");

或:

printf("\nBefore Fork");
fflush(stdout);

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 1970-01-01
    • 2014-06-17
    • 2017-09-22
    • 1970-01-01
    • 2022-01-05
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多