首页 > 解决方案 > 如何在 fork 上的子进程期间在字符串上打印 \n

问题描述

我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>

int main(){
    fork();
    printf("Show me the new line before the pid child dies \n");
    return 0;
}

输出:

>Show me the new line before the pid child dies Show me the new line before the pid child dies"\n
>

我的预期结果是将 '\n' 显示为字符串的一部分并有两个单独的行,如下所示:

>string1 \n
>string2 \n
>

但我得到以下信息:

>string1 string2 \n
>

我尝试使用 fflush(stdout) 但没有任何区别。

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>

int main(){
    fork();
    printf("Show me the new line before the pid child dies \n");
    fflush(stdout);
    return 0;
}

相同的输出:

>"Show me the new line before the pid child dies Show me the new line before the pid child dies"
>

我该怎么做才能得到以下输出:

>"Show me the new line before the pid child dies \n"
> Show me the new line before the pid child dies \n"
>

更新:

如果我按如下方式运行它,它会向我显示正确的行(如我所愿):

终端/powershell上的命令

 .\f.exe > f.out

输出:

1 Show me the new line before the pid child dies 
2 Show me the new line before the pid child dies 
3 

然后我正在改变我的问题:我真的可以得到与我的 f.out 文件上显示的完全相同的输出吗(vs code / powershell)?

我在 Windows 上运行 MS Visual Studio。

标签: cwindowsvisual-studiofork

解决方案


在对父线程和子线程的调用fork()都尝试同时打印之后,您可能遇到了竞速情况。这种情况下的行为是未定义的。家庭作业的整个想法可能就是教你这一点。您应该使用某种线程间通信,或者只是在父进程中等待(或在子进程中没关系)。

if (fork()) sleep(1);

更新:

仔细阅读您的输出行后,我意识到您的练习可能是学习在父进程中等待直到孩子死亡,这是这样实现的:

if (fork() != 0) wait(NULL);


推荐阅读