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 fork1
shell1: shell1.c
	g++ -g -Wall shell1.c ../lib/libapue.a -I ../include -o shell1
shell2: shell2.c
	g++ -g -Wall shell2.c ../lib/libapue.a -I ../include -o shell2
fork1: fork1.c
	g++ -g -Wall fork1.c ../lib/libapue.a -I ../include -o fork1
clean:
	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 vfork1
shell1: shell1.c
	g++ -g -Wall shell1.c ../lib/libapue.a -I ../include -o shell1
shell2: shell2.c
	g++ -g -Wall shell2.c ../lib/libapue.a -I ../include -o shell2
fork1: fork1.c
	g++ -g -Wall fork1.c ../lib/libapue.a -I ../include -o fork1
vfork1: vfork1.c
	g++ -g -Wall vfork1.c ../lib/libapue.a -I ../include -o vfork1
clean:
	rm shell1 shell2 fork1 vfork1

 

技术分享

技术分享

技术分享

技术分享

 

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。