In the process of learning about forking and processes in the C language I faced some points that are still not clear to me for example the use of the function wait()
I have some examples of when the function worked in a different way that I hoped for. can I get a clear explanation on why it works this way?
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#define N 10
int main(){
int c1, c2, t, i;
c2 = 1;
c1 = 0;
for(i = 1; i < N; i++){
switch(fork()){
case -1:
printf("Error creating process\n");
return -1;
case 0:
t = c2;
c2 = c1 + c2;
c1 = t;
break;
default:
printf("%d ", c2);
wait(NULL);
return 0;
break;
}
}
if(i == N){
printf("%d ", c2);
}
return 0;
}
for some reason this code prints the Fibonacci sequence in reverse even though the parent process is printing before using wait.
When I tried to put the wait function above the printf()
function in the parent process it did the same thing and printed the Fibonacci sequence in reverse. Can someone please explain to me why is this happening?
printf("%d ", c2);
does not send characters to the terminal. It sends characters to the standard output stream.
The standard output stream is buffered.1 It stores characters given to it in a buffer. It only sends the characters to the operating system, to be written to the terminal, when the buffer is full, when a newline character is given to it, or when the stream is flushed (which can be done with fflush(stdout)
and which is done automatically when the program exits normally).
So what happens is your first process sends “1 ” to its standard output stream and then waits. Then your second process sends “1 ” and waits. Your third process sends “2 ” and waits. And so on, until the last process sends “55 ” and then exits. When it exits, its buffer is flushed, sending “55 ” to the terminal. Then the previous process exits and sends “34 ”. This continues with each process exiting, until the first process exits and sends its “1 ” to the terminal.
1 Ordinarily, a stream to a terminal is line buffered, in which newline character causes the buffer contents to be sent. If the stream is directed to a file, it is fully buffered, in which buffer contents are sent only when the buffer is full or there is a flush request. An output stream can also be unbuffered, in which case every character sent to it is immediately sent to the operating system, not held in a buffer. These behaviors are a mix of what the C standard requires and how various operating systems behave.