使用 printf 时,C fork 是 parent 的副本
C fork is a copy of parent when using printf
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
write(STDOUT_FILENO,"1",1);
if(fork() > 0) {
write(STDOUT_FILENO,"2",1);
write(STDOUT_FILENO,"3",1);
}
else {
write(STDOUT_FILENO,"4",1);
write(STDOUT_FILENO,"5",1);
}
write(STDOUT_FILENO,"\n",1);
return 0;
}
输出为1 2 3 \n 4 5 \n
为什么如果我替换 printf
(最后没有换行符)的所有写入函数,如 write(STDOUT_FILENO,"1",1)==printf("1")
,我得到 1 2 3 \n 1 4 5 \n
,如 child正在复制叉子上方的行?
是的,这是因为 stdout 流被缓冲,直到它按照这个 post Why does printf not flush after the call unless a newline is in the format string?. So when you form a new process this buffer is copied to the child's stdout buffer since we are essentially making a new memory space for the child. (Actually not quite, see Specifically, how does fork() handle dynamically allocated memory from malloc() in Linux? )
这将起作用
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
printf("1");
fflush(stdout);
if(fork() > 0) {
printf("2");
printf("3");
} else {
printf("4");
printf("5");
}
printf("\n");
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
write(STDOUT_FILENO,"1",1);
if(fork() > 0) {
write(STDOUT_FILENO,"2",1);
write(STDOUT_FILENO,"3",1);
}
else {
write(STDOUT_FILENO,"4",1);
write(STDOUT_FILENO,"5",1);
}
write(STDOUT_FILENO,"\n",1);
return 0;
}
输出为1 2 3 \n 4 5 \n
为什么如果我替换 printf
(最后没有换行符)的所有写入函数,如 write(STDOUT_FILENO,"1",1)==printf("1")
,我得到 1 2 3 \n 1 4 5 \n
,如 child正在复制叉子上方的行?
是的,这是因为 stdout 流被缓冲,直到它按照这个 post Why does printf not flush after the call unless a newline is in the format string?. So when you form a new process this buffer is copied to the child's stdout buffer since we are essentially making a new memory space for the child. (Actually not quite, see Specifically, how does fork() handle dynamically allocated memory from malloc() in Linux? )
这将起作用
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
printf("1");
fflush(stdout);
if(fork() > 0) {
printf("2");
printf("3");
} else {
printf("4");
printf("5");
}
printf("\n");
return 0;
}