c - 如何在 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。
解决方案
在对父线程和子线程的调用fork()
都尝试同时打印之后,您可能遇到了竞速情况。这种情况下的行为是未定义的。家庭作业的整个想法可能就是教你这一点。您应该使用某种线程间通信,或者只是在父进程中等待(或在子进程中没关系)。
if (fork()) sleep(1);
更新:
仔细阅读您的输出行后,我意识到您的练习可能是学习在父进程中等待直到孩子死亡,这是这样实现的:
if (fork() != 0) wait(NULL);
推荐阅读
- google-app-engine - 谷歌云Appengine标准环境部署使用Admin API:“Cant find import”错误
- angular - 角度2反应形式无需触摸即可获取输入值
- vb.net - 来自 storageFile 的裁剪图像在发布模式下变为空,但在调试模式下有效
- r - 从数据列中删除点
- perl - 带有 Net::IP 的下一个块的第一个 IP
- azure-web-app-service - 如何防止直接访问托管在 Azure 应用服务中的 API
- php - 两个变量之间的减法不起作用,如何解决?
- python - 添加/删除包含多个小部件pyqt的布局
- reactjs - Invariant Violation:Invariant Violation:元素类型无效:预期为字符串(对于内置组件)但得到:未定义
- typescript - 强制对象至少有一个键( Object.keys(o).length > 0 )