首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。