首页 > 代码库 > UNIX环境高级编程第8章进程控制 8.3fork 文件共享 vfork

UNIX环境高级编程第8章进程控制 8.3fork 文件共享 vfork

 

技术分享

技术分享

技术分享

 

技术分享

技术分享

 

#include "apue.h"/* syj 20140112 */int glob = 6; /* external variable in initialized data */char buf[] = "a write to stdout\n";int main(void){    int var; /* automatic variable on the stack */    pid_t pid;    var = 88;    if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)        err_sys("write error");    printf("before fork\n\n"); /* we don‘t flush stdout */    /* fflush(stdout); */           /* if comments this line, the child will flush the stdout */    if ((pid = fork()) < 0)    {        err_sys("fork error");    }    else if (pid == 0)    {                                              /* child, first flush buffer */        printf("hello, I am child process\n");        glob++;                               /* modify variables */        var++;    }    else    {        sleep(3);                             /* parent */        printf("hello, I am parent process\n");    }    if (0 == pid) /* for the child process, variable pid is 0 */    {        printf("hello, I am child process, variable pid is 0\n");    }    else          /* for the parent process, variable pid is child pid */    {        printf("hello, I am parent process, variable pid is child pid\n");    }    printf("pid = %d, pid = %d, glob = %d, var = %d\n\n\n", pid, getpid(), glob, var);    return 0;}
all: shell1 shell2 fork1shell1: shell1.c	g++ -g -Wall shell1.c ../lib/libapue.a -I ../include -o shell1shell2: shell2.c	g++ -g -Wall shell2.c ../lib/libapue.a -I ../include -o shell2fork1: fork1.c	g++ -g -Wall fork1.c ../lib/libapue.a -I ../include -o fork1clean:	rm shell1 shell2 fork1

 

技术分享

技术分享

技术分享

技术分享

技术分享

技术分享

 

技术分享

 

#include "apue.h"int glob = 6; /* external variable in initialized data */int main(void){    int var; /* automatic variable on the stack */    pid_t pid;    var = 88;    printf("before vfork\n"); /* we don‘t flush stdio */    if ((pid = vfork()) < 0)     {        err_sys("vfork error");    }    else if (pid == 0)    {   /* child */        glob++; /* modify parent‘s variables */        var++;        _exit(0); /* child terminates */    }    /*     * Parent continues here.     */    printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);    return 0;}
all: shell1 shell2 fork1 vfork1shell1: shell1.c	g++ -g -Wall shell1.c ../lib/libapue.a -I ../include -o shell1shell2: shell2.c	g++ -g -Wall shell2.c ../lib/libapue.a -I ../include -o shell2fork1: fork1.c	g++ -g -Wall fork1.c ../lib/libapue.a -I ../include -o fork1vfork1: vfork1.c	g++ -g -Wall vfork1.c ../lib/libapue.a -I ../include -o vfork1clean:	rm shell1 shell2 fork1 vfork1

 

技术分享

技术分享

技术分享

技术分享

 

技术分享

UNIX环境高级编程第8章进程控制 8.3fork 文件共享 vfork