Last active
May 9, 2018 04:10
-
-
Save pileon/9441a2b15ea498191715cda13c966ca1 to your computer and use it in GitHub Desktop.
Code testing possible forking and file bug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 2 8 1 4 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.