作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我的代码:
#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/
我是一名优秀的程序员,十分优秀!