Linux programming | fork function explanation, linux programming fork Function

Source: Internet
Author: User
Tags glob

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.