Search code examples
clinuxfile-ioforkrace-condition

Why does my forked process sometimes overwrite data in a file?


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:

  • The file sometimes contains "Child\nParent\n" and other times "Parent\nChild\n"
  • In some cases, the output is corrupted or mixed
  • I expected each process to write separately, but they seem to interfere with each other

Question:

  1. Why is this happening?
  2. How can I ensure correct, separate writes from each process?

Solution

  • 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.