%20%E5%9C%A8%20fork()%20%E4%B9%8B%E5%89%8D%E8%B0%83%E7%94%A8%EF%BC%8C%E4%BD%86%E6%AF%8F%E6%AC%A1%E8%B0%83%E7%94%A8%20fork()%20%E6%97%B6%E9%83%BD%E4%BC%9A%E5%B0%86%20printf()%20%E5%BE%AA%E7%8E%AF%E8%BE%93%E5%87%BA%E5%88%B0%20stdout%E3%80%82%E4%B8%BA%E4%BB%80%E4%B9%88%20'%5Cn'%20%E5%8F%AF%E4%BB%A5%E8%A7%A3%E5%86%B3%E8%BF%99%E4%B8%AA%E9%97%AE%E9%A2%98%EF%BC%9F%20.png)
当我玩的时候,fork()
我注意到一种相当奇怪的行为,但我无法弄清楚为什么会发生这种情况。
在下面的示例中,每次调用之前调用fork()
的输出printf()
都会打印到 stdout。test
输出中的值表明printf()
并没有真正再次执行,否则test
每次都会增加。
\n
更奇怪的是(或者可能是解决方案的关键),当我添加到 printf() 格式字符串的末尾时,这种行为不会发生。
有谁知道为什么会发生这种情况?也许它与标准输出缓冲区有关?我对这个东西不太熟悉。
或者我做错了什么可怕的事情?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(char* args) {
pid_t pid;
int wstatus;
int test = 0;
printf("\n[%d] parent start | test = %d ", getpid(), test++);
// This works fine
//printf("\n[%d] parent start | test = %d \n", getpid(), test++);
for(int i = 0; i < 5; i++) {
if((pid = fork()) == 0) {
//printf("\n[%d] Child spawned ", getpid());
exit(0);
}
//printf("\n[%d] Printing with fork() commented out works fine", getpid());
}
while(wait(&wstatus) > 0);
printf("\n[%d] parent end\n\n", getpid());
return 0;
}
输出:
[342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0
[342470] parent end
如果有什么用的话
$ uname -a
Linux Aspire 5.4.0-26-generic #30-Ubuntu SMP Mon Apr 20 16:58:30 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
答案1
已将printf
文本写入标准输出buffer,最终通过调用写入到 fork 的每个分支中exit
。