The following is an instance of the fork function.
[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
Int glob = 6;
Char buf [] = "a write to stdout \ n ";
Int main (void)
{
Int var;
Pid_t pid;
Var = 88;
If (write (STDOUT_FILENO, buf, sizeof (buf)-1 )! = Sizeof (buf)-1)
Printf ("error: write error \ n ");
Printf ("before fork \ n ");
If (pid = fork () <0 ){
Printf ("error: fork error \ n ");
} Else if (pid = 0 ){
Glob ++;
Var ++;
} Else {
Sleep (2 );
}
Printf ("pid = % d, glob = % d, var = % d \ n", getpid (), glob, var );
Exit (0 );
}
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
Int glob = 6;
Char buf [] = "a write to stdout \ n ";
Int main (void)
{
Int var;
Pid_t pid;
Var = 88;
If (write (STDOUT_FILENO, buf, sizeof (buf)-1 )! = Sizeof (buf)-1)
Printf ("error: write error \ n ");
Printf ("before fork \ n ");
If (pid = fork () <0 ){
Printf ("error: fork error \ n ");
} Else if (pid = 0 ){
Glob ++;
Var ++;
} Else {
Sleep (2 );
}
Printf ("pid = % d, glob = % d, var = % d \ n", getpid (), glob, var );
Exit (0 );
}
Then execute the output
Jay @ jay-vibox :~ /Workspace/UNIX/8-1 $ cc main. c
Jay @ jay-vibox :~ /Workspace/UNIX/8-1 $./a. out
A write to stdout
Before fork
Pid = 2917, glob = 7, var = 89
Pid = 2916, glob = 6, var = 88
------------------------------------------------
Jay @ jay-vibox :~ /Workspace/UNIX/8-1 $./a. out> tmp. out
Jay @ jay-vibox :~ /Workspace/UNIX/8-1 $
Jay @ jay-vibox :~ /Workspace/UNIX/8-1 $
Jay @ jay-vibox :~ /Workspace/UNIX/8-1 $ cat tmp. out
A write to stdout
Before fork
Pid = 2925, glob = 7, var = 89
Before fork
Pid = 2924, glob = 6, var = 88
-----------------------------------------------------------
Generally, it is not clear whether to execute the parent process or child process after fork.
When writing a standard output, we subtract 1 from the buf length as the number of output bytes to avoid terminating null characters. Strlen calculates the length of a string that does not include the ending null character, while sizeof calculates the buffer length that includes the ending null byte. Another difference between the two is that strlen is used for callback function calls. For sizeof, the length of the buffer is fixed because it is initialized with a string, therefore, sizeof calculates the buffer length during compilation.
When the program is run in interactive mode, only the row output by the printf is obtained once, because the standard output buffer is flushed by line breaks.
However, when the standard output is redirected to a file, the printf output is obtained twice. The reason is that when fork previously called printf once, but when fork was called, the row of data is still in the buffer, and then the data space of the parent process is copied to the child process, the buffer is also copied to the sub-process. At that time, the Parent and Child processes each had a standard IO buffer with modified content.
Author: zhangjie201412