Description:
How many "-" are output by each of the following two programs?
#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(void){ int i; for(i=0; i<2; i++) { fork(); printf("-"); } return 0;}
#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(void){ int i; for(i=0; i<2; i++) { fork(); printf("-\n"); } return 0;}
Answer: The first program outputs 8 "-", and the second program outputs 6 "-"
Resolution (Source Network ):
Important features of fork:
- Fork () system call is a system call in Unix to create a sub-process with its own process. One call and two returns. If the return value is 0, it is a sub-process. If the return value is greater than 0, it is the parent process (the return value is the pid of the child process)
- At the call of fork (), the entire parent process space is copied to the child process as is, including commands, variable values, program call stacks, environment variables, buffers, etc.
The first program outputs 8 "-" because the printf ("-"); statement has buffer, so for the above program, printf ("-"); put "-" into the cache and there is no real output,During fork, the cache is copied to the sub-process space.So, two more, eight instead of six.
The second program outputs 6 "-", which distinguishes the first program: printf ("-\ n"); here the program Encounters "\ n", or EOF, the data is flushed out of the buffer zone if the buffer zone is full or the file descriptor is closed or flushed or the program exits. It should be noted that the standard output is a row buffer, so the buffer will be flushed out when "n" is encountered, but for the disk block device, "n" does not cause the buffer to be flushed out. It is a full buffer. You can use setvbuf to set the buffer size or use fflush to flush the cache.
PS: Unix devices have the concepts of "Block devices" and "character devices". Block devices are devices that access data in one piece, A character device is a device that accesses one character at a time. Disks and memory are both Block devices. Character devices such as keyboards and serial ports.Block devices generally have caches, while character devices generally do not..
The following figure shows the online legend. Two green outputs are displayed: "-", two brown outputs, one light green, and one pink, in the first program, the lowest layer in the first program will put one in each buffer, and the cached characters will be output at the end, so there are two in total. To sum up the first program 8 "-", the second program 6 "-".
The first program:
The second program: