等待无法同步三个进程
我是一名新的 C 开发人员。我正在尝试使用以下代码同步三个进程来打印 [FATHER][SON][GRANDSON][FATHER][SON][GRANDSON]:
int main(int argc, char **argv)
{
int c = 0;
while (c<2)
{
c++;
printf("[FATHER]");
pid_t son = fork();
if (son == 0)
{
printf("[SON]");
pid_t grandson = fork();
if (grandson == 0)
{
printf("[GRANDSON]");
return 0;
}
wait(NULL);
return 0;
}
wait(NULL);
};
}
相反,我得到以下输出: [FATHER][SON][GRANDSON][FATHER ][儿子][父亲][父亲][儿子][孙子][父亲][父亲][儿子][父亲][父亲]
使用等待代码时我是否误解或遗漏了什么?非常非常感谢。
Im a new C dev. I'm trying to sync three processes to print [FATHER][SON][GRANDSON][FATHER][SON][GRANDSON] with this code:
int main(int argc, char **argv)
{
int c = 0;
while (c<2)
{
c++;
printf("[FATHER]");
pid_t son = fork();
if (son == 0)
{
printf("[SON]");
pid_t grandson = fork();
if (grandson == 0)
{
printf("[GRANDSON]");
return 0;
}
wait(NULL);
return 0;
}
wait(NULL);
};
}
Instead, im getting this output: [FATHER][SON][GRANDSON][FATHER][SON][FATHER][FATHER][SON][GRANDSON][FATHER][FATHER][SON][FATHER][FATHER]
Am i misunderstanding or missing something when using wait on code? Thank you very very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与其在每次调用
printf
后调用fflush
,不如使用write
系统调用来打印到stdout
(如有必要,首先使用sprintf
格式化输出字符串)。write
系统调用执行无缓冲写入,这将使您不必每次都记住调用fflush
。您甚至可以使用可变参数宏来避免总是先写入
sprintf
行,然后再写入write
行。Instead of calling
fflush
after every call toprintf
, it'd be better if you used thewrite
system call to print tostdout
(format the output string usingsprintf
first if necessary). Thewrite
system call does unbuffered writing, which would prevent you from having to remember to callfflush
every time.You could even use a variadic macro to avoid writing always a
sprintf
line followed by awrite
line.