我有以下代码 它打印到屏幕上:哈哈 到文件:
haha
hello
Father finished
如果我删除第 6 行和第 7 行,我会得到不同的结果 为什么?
int main()
{
// creates a new file having full read/write permissions
int fd = open("myfile", O_RDWR|O_CREAT, 0666);
write(fd, "haha\n", 5);
close(fd); // line 6
fd = open("myfile", O_RDWR); // line 7
close(0);
close(1);
dup(fd);
dup(fd);
if (fork() == 0)
{
char s[100];
dup(fd);
scanf("%s", s);
printf("hello\n");
write(2, s, strlen(s));
return 0;
}
wait(NULL);
printf("Father finished\n");
close(fd);
return 0;
}
最佳答案
尝试注释掉scanf(),重新编译并重新运行。尝试读取超出 EOF 的 scanf() 可能会在 stdio 库内部缓冲区中执行某些操作,从而导致 printf() 缓冲区在进程 _exit 时未刷新出现此问题。只是猜测...
关于c - 打开描述符和关闭,为什么重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17239441/