Process shaping with C

I follow this tutorial about fork() , but this is not clear to me.

Both processes will begin execution in the next statement following the fork () call. In this case, both processes will start execution in the assignment statement, as shown below: enter image description here

According to this sentence, this script

 printf("before "); fork(); printf("after "); 

should print this: (Since the child process starts with printf("after") )

 before after after 

but he prints this instead:

 before after before after 

So, did the child process start on the first line of the file? Can you tell me what happened to my code? I misunderstood this sentence?

EDIT

Script compiled and executed on OS X

+5
source share
4 answers

When you create a new process, it inherits all the variables of the original process - thus, all the buffers. Since the "before" is not yet cleared and is still in the buffer, the child process will also contain this line in the buffer and print it. Therefore, before you deploy the process, you must call fflush(stdout); .

+7
source

You understood the sentence correctly, but ...

When you call fork , it takes a snapshot of the process and creates an exact duplicate. Therefore, if there is data in the stdout buffer waiting to be written to the console, then this data will be in the child output buffer after fork, as well as in the parent buffer.

There are two ways to clear the output buffer in front of the plug. You can add a new line \n at the end of printf

 printf( "before\n" ); fork(); printf( "after\n" ); 

or you can use fflush function

 printf( "before " ); fflush( stdout ); fork(); printf( "after " ); 
+3
source

This is because the "before" is buffered and output only when this buffer is flushed. This happens when two processes complete.

+2
source

If you call fflush on stdout before fork , you will see the expected result. Typically, C buffered IOs will not play well when you perform operations at the OS level.

The memory buffer associated with the standard output is cloned to fork , including any previously buffered output. This is why you see the "earlier" twice.

+1
source

Source: https://habr.com/ru/post/1208969/


All Articles