I was writing sample code and trying to understand what happens when two processes open the file in append mode and then both perform write.

process1.c

#include <stdio.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    int fd = open("hello.txt", O_WRONLY| O_APPEND);
    off_t curpos;
     curpos = lseek(fd, 0, SEEK_CUR);
     printf("curpos:%lu\n", curpos);

    perror("open");
    write(fd, "hello", sizeof("hello"));
    close(fd);
    return 0;
}

process2.c

int main(int argc, char *argv[])
{
    off_t curpos;
    int fd = open("hello.txt", O_WRONLY | O_APPEND);
     curpos = lseek(fd, 0, SEEK_CUR);
     printf("curpos:%lu\n", curpos);

    perror("open");

    getchar();
     curpos = lseek(fd, 0, SEEK_CUR);
     printf("curpos:%lu\n", curpos);
    write(fd, "world", sizeof("world"));
    close(fd);
    return 0;
}

When i run first process2, it will open the file and it will wait for user input as there is getchar, i now run process1, and finally continue the process2.

Why is the output : "helloworld" and not only "world"

0 Answers