Skip to content

Instantly share code, notes, and snippets.

@futureperfect
Created January 13, 2018 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save futureperfect/c020cd00d58b47574a2118f66506cf9d to your computer and use it in GitHub Desktop.
Save futureperfect/c020cd00d58b47574a2118f66506cf9d to your computer and use it in GitHub Desktop.
How do concurrent writes by parent and child processes behave with a shared file descriptor?
/* Write a program that opens a file (with the open() system call) and then
* calls fork() to create a new process. Can both the child and parent access
* the file descriptor returned by open()? What happens when they are writing to
* the file concurrently, i.e., at the same time? */
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd = open("./test.txt", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU);
if (fd < 0) {
fprintf(stderr, "Error opening file for writing. Exiting...\n");
exit(1);
}
int rc = fork();
if (rc < 0) {
fprintf(stderr, "Error forking. Exiting...\n");
exit(1);
} else if (rc == 0) {
printf("I'm a child. Writing childish things to file.\n");
for(int i = 0; i < 1000; i++)
{
int result = write(fd, "WAAAAAAAAAAAAAAHHHHHHH :(\n", 26);
fprintf(stdout, "Result = %d\n", result);
}
} else {
printf("I'm a parent. Writing parental things to file.\n");
for(int i = 0; i < 1000; i++)
{
int result = write(fd, ".....why............\n", 21);
fprintf(stdout, "Result = %d\n", result);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment