此问题已经在这里有了答案:
我得到了下一个代码(为解释我做了评论):
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
// Outputs to stdout: ""Hello from son\n""
int main() {
/* Clone the calling process, creating an exact copy.
Return -1 for errors, 0 to the new process,
and the process ID of the new process to the old process. */
int res = fork();
// For new process, res == 0
if (res != 0) {
// Called by PARENT
// Close the file descriptor FD.
close(STDOUT_FILENO);
}
// O_RDWR - open for ReaD and WRite
// Open FILE and return a new file descriptor for it, or -1 on error.
// Failed operation because no such file
int fd = open("myFile", O_RDWR);
if (res != 0) {
// Write formatted output to **stdout**
printf("Hello from father\n");
} else {
printf("Hello from son\n");
}
}
我的期望是当父进程关闭文件描述符时,什么都不会打印到stdout
,有人可以解释当前的行为吗?
这是我们查看您的代码时的理论行为。但是实际上这可能有所不同,因为在父级关闭文件描述符之前,儿子可能有时间打印到STDOUT
。