Linux programming | fork function explanation, linux programming fork Function
[Root @ slave bdkyr] # cat fork_test.c
/*
* Create by bdkyr
* Date 2015-1-22
*/
# Include <stdlib. h>
# Include <stdio. h>
# Include <errno. h>
# Include <unistd. h>
# Include <stdarg. h>
# Include <string. h>
# Define MAXLINE 4096/* max line length */
Int glob = 6;
Char buf [] = "a write to stdout \ n ";
Void err_sys (const char * fmt ,...);
Static void err_doit (int, int, const char *, va_list );
Int main (void ){
Int var;
Pid_t pid;
Var = 88;
If (write (STDOUT_FILENO, buf, sizeof (buf)-1 )! = Sizeof (buf)-1)
Err_sys ("write error ");
Printf ("before fork \ n ");
If (pid = fork () <0 ){
Err_sys ("fork error ");
} Else if (pid = 0 ){
Glob ++;
Var ++;
} Else {
Sleep (2 );
}
Printf ("pid = % d, glob = % d, var = % d \ n", getpid (), glob, var );
Exit (0 );
}
Void err_sys (const char * fmt ,...){
Va_list ap;
Va_start (ap, fmt );
Err_doit (1, errno, fmt, ap );
Va_end (ap );
Exit (1 );
}
Static void err_doit (int errnoflag, int error, const char * fmt, va_list ap ){
Vsnprintf (buf, MAXLINE, fmt, ap );
If (errnoflag)
Snprintf (buf + strlen (buf), MAXLINE-strlen (buf), ": % s", strerror (error ));
Strcat (buf, "\ n ");
Fflush (stdout );
Fputs (buf, stderr );
Fflush (NULL );
}
[Root @ slave bdkyr] # gcc fork_test.c-o fork_test
[Root @ slave bdkyr] #./fork_test
A write to stdout
Before fork
Pid = 5209, glob = 7, var = 89
Pid = 5208, glob = 6, var = 88