Skip to content

Instantly share code, notes, and snippets.

@pileon
Last active May 9, 2018 04:10
Show Gist options
  • Save pileon/9441a2b15ea498191715cda13c966ca1 to your computer and use it in GitHub Desktop.
Save pileon/9441a2b15ea498191715cda13c966ca1 to your computer and use it in GitHub Desktop.
Code testing possible forking and file bug
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int order;
FILE* file = fopen("sample_input.txt", "r");
if (file != NULL)
{
printf("parent process: %d\n", getpid());
int n;
while ((n = fscanf(file, "%d", &order)) == 1)
{
int f = fork();
if (f == 0)
{
break;
}
}
//fclose(file);
printf("process %d (parent %d)\n", getpid(), getppid());
}
}
@pileon
Copy link
Author

pileon commented May 9, 2018

On Linux (kernel version 4.16.0) and using GCC (tested with version 7.3.0) and libc version 2.27, this program will not stop reading from the file after reading the last value. Instead the parent process will repeatedly read the last value from the file and create more and more processes.

On my system the parent process will stop reading after a while though.

If the fclose call is uncommented, then it will all work okay, with the parent process stop reading after the last value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment