I am creating a multi process program. When I tried to call fork() in a for loop using if(f == 0) break;
. I got the desired number of child processes.
However now, I am dealing with an input file, and the desired number of processes is not known initially. Here is the smallest possible example of my code.
FILE* file = fopen("sample_input.txt", "r");
while(fscanf(file, "%d", &order) == 1){
f = fork();
if(f == 0){
break;
}
}
example sample_input.txt
:
5 2 8 1 4 2
Now thousands of child processes are being created (I want 6, the number of integers in the file), what could be the reason ? Is it something to do with the file pointer ?
Edit: I did some debugging with console outputs, the child processes are indeed breaking out of the loop. However the parent keeps reading a small file over and over. If I remove fork()
, the loop executes 6 times as intended.
Edit2: I have a theory, I can't prove it maybe you can help me. It could be the situation that the file pointer is shared between processes, when a child exits, it closes the file and when the parent tries to read again, it just starts from the beginning (or some other weird behavior). Could it be the case ?