首页 > 解决方案 > c语言中多进程的输出有什么问题?

问题描述

我有以下代码:

int main()
{
    for (int i = 0; i < 3; i++) {
        int t = fork();
        if (t == 0) {
            printf("child %d id: %ld from pid: %ld\n", i, (long)getpid(), (long)getppid());
            exit(0);
        }
        else if (t > 0) {
            wait(NULL);
            printf("father %d id: %ld from pid: %ld\n", i, (long)getpid(), (long)getppid());
        }
    }
    return(0);
}

当我运行输出是: 输出1

当我在 t>0 时删除 printf 中的“\n”时,输出为: 输出2

第二个输出如何比第一个输出更多?请!!

抱歉,我意识到这是关于 C 中缓冲区的问题,我只是在我的多线程分配中遇到这个问题,而我是 C 中的新手并且还不知道这一点。我只是认为它来自多线程的问题,所以我在这里问。

标签: cprocessoutputfork

解决方案


您需要记住,printf这并不一定会导致写入任何数据。相反,printf只需将数据写入根据需要刷新的内部缓冲区。

让我们稍微简化一下代码并展开循环以检查发生了什么

int
main(void)
{
        int t, i = 0;
        t = fork();
        if( t == 0 ) {
                printf("child %d id: %ld from pid: %ld\n",
                        i, (long)getpid(), (long)getppid());
                exit(0);
        } else if( t > 0 ) {
                wait(NULL);
                printf("parent %d id: %ld from pid: %ld",
                        i, (long)getpid(), (long)getppid());
        }
        /* The output buffer now contains "parent N id ..."
           but the parent has not yet written any data.  */
        i += 1;
        t = fork();
        if( t == 0 ) {
                /* Here, the output buffer still contains "parent N id ..." */
                printf("child %d id: %ld from pid: %ld\n",
                        i, (long)getpid(), (long)getppid());
                /* The newline above causes the buffer to be flushed, 
so now this child writes "parent N id ...child M id: ..." */
                exit(0);
      ... 

如果您\n在父级的 printf 中包含 ,这会导致(在某些情况下)输出缓冲区被刷新,以便在您调用时它是空fork的,并且子级不会写入附加数据。请注意,如果您将输出重定向到文件,您可能会得到不同的行为,因为\n在这种情况下可能不会导致刷新。如果要确保在任何给定点刷新缓冲区,请调用fflush.


推荐阅读