c - 如何在 fork 的子进程期间在字符串上打印\n

标签 c windows visual-studio fork

我的代码:

#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 

然后我正在改变我的问题:我真的可以在我的终端上获得完全相同的输出(与代码/powershell 相比),因为我正在获取我的 f.out 文件吗?

我在 Windows 上运行 MS Visual Studio。

最佳答案

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

if (fork()) sleep(1);

更新:

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

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

关于c - 如何在 fork 的子进程期间在字符串上打印\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53752283/

相关文章:

c++ - 删除 ListView 中特定项目的复选框

c - 无法连接 winsock - c 上的错误 10049

asp.net - 在 Visual Studio 中格式化 aspx 文件

c - 如何在 C 中使用 void 指针作为函数返回类型

c - 如何在C中复制结构的唯一成员

您可以允许几种类型的指针之一作为参数而不使用 void* 吗?

c - C 中的 Windows 用户主文件夹 (MinGW)

c++ - 如何从 CMake 中隐藏 Visual Studio 中的目标

c++ - VS2010中的常量问题

c - 如何打印自定义字符