我有以下 C 代码,在 之后从父进程和子进程写入文件fork()
。但是, 中的输出testfile.txt
有时会损坏或出现意外顺序。
我附上了代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("testfile.txt", O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
perror("open");
return 1;
}
if (fork() == 0) {
// Child process
write(fd, "Child\n", 6);
close(fd);
} else {
// Parent process
write(fd, "Parent\n", 7);
close(fd);
}
return 0;
}
问题:
- 文件有时包含
"Child\nParent\n"
,有时包含"Parent\nChild\n"
- 在某些情况下,输出被损坏或混杂
- 我期望每个过程单独写入,但它们似乎互相干扰
问题:
- 为什么会发生这种情况?
- 我如何确保每个进程的写入正确且独立?