Some examples of Buffer
#include
#include
#include
int main(){ pid_t pid = 0; printf("test\n"); pid = fork(); if (pid == 0) { exit(0); } return 0;}
The output of the above Code is as follows:
Test
However, if you run./fork> out.txt
You will find that the content in out.txt is:
Test
Test
This is because the pintf () function maintains a buffer. When the buffer is output to the terminal, the row is buffered, while in other cases, the buffer is full. In this way, although a new process is generated for fork when it is output to the terminal, it is output to the terminal, all of which are row buffering. After a row is output, refresh the buffer and output it to the screen, there is no data in the buffer, so after the fork sub-process exits, although it will refresh the buffer, but the buffer has no content, all, only one test is output. But when the output is redirected to out.txt, printf () is the full buffer. When the parent process space is running, the test of printf (); is not output, but is stored in the buffer. After fork, when a sub-process is generated, we know that the sub-process replicates everything from the parent process to another process ID. In this way, the buffer content is also copied. In this way, when the parent process exits, refresh the buffer and output a test. When the child process exits, refresh the buffer. As we have already described, when the fork sub-process exits, the buffer of the parent process should not be completely copied, so there is also a test in the buffer of the child process, so the child process also outputs a test.
Of course, in linux, note the difference between exit () and _ exit (). Apart from the exit function that exit () needs to execute atexit () registration, another operation than _ exit () is to refresh the buffer,
#include
#include
#include
int main(){ pid_t pid = 0; printf("test\n"); pid = fork(); if (pid == 0) { _exit(0); } return 0;}
After the above changes, the code will be compiled and run. In the first example, the code is run in two ways, and only one test is output.