I have the following C code that writes to a file from both the parent and child process after a fork()
. However, the output in testfile.txt
is sometimes corrupted or in an unexpected order.
I'm attaching the code:
#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;
}
Issue:
"Child\nParent\n"
and other times "Parent\nChild\n"
Question:
Open the file with flag `O_APPEND` to avoid corruption:
The man page tells: "The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2). The modification of the file offset and the write operation are performed as a single atomic step."
The output order is not controlled by this flag.