linux创建进程fork函数和vfork函数
生活随笔
收集整理的這篇文章主要介紹了
linux创建进程fork函数和vfork函数
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#include <unistd.h>pid_t fork(void);#include <sys/types.h>#include <unistd.h>pid_t vfork(void);
返回:子進(jìn)程中為0,父進(jìn)程中為子進(jìn)程ID,出錯(cuò)返回 -1
?
fork創(chuàng)建的新進(jìn)程被稱為子進(jìn)程,該函數(shù)被調(diào)用一次但是返回兩次,兩次返回的區(qū)別是:在子進(jìn)程中的返回值是,在父進(jìn)程中的返回值是新的子進(jìn)程的進(jìn)程ID;
創(chuàng)建子進(jìn)程,父進(jìn)程哪個(gè)先運(yùn)行根據(jù)系統(tǒng)的調(diào)度且復(fù)制父進(jìn)程的內(nèi)存空間。
vfork函數(shù),創(chuàng)建子進(jìn)程,但是子進(jìn)程先運(yùn)行且不復(fù)制父進(jìn)程的內(nèi)存空間。
?
fork函數(shù)示例:
#include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <errno.h>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)perror("write error");printf("before fork\n"); /* we don't flush stdout */if ((pid = fork()) < 0) {perror("fork error");} else if (pid == 0) { /* child */glob++; /* modify variables */var++;} else {sleep(2); /* parent */}printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);exit(0); }編譯之后運(yùn)行結(jié)果:
andrew@andrew-Thurley:~/work/apue.2e$ ./a.out a write to stdout before fork pid = 16935, glob = 7, var = 89 pid = 16934, glob = 6, var = 88?
#include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <errno.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) {perror("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);exit(0); }?
編譯之后運(yùn)行結(jié)果:
andrew@andrew-Thurley:~/work/apue.2e$ ./a.out before vfork pid = 17047, glob = 7, var = 89?
?
?
總結(jié)
以上是生活随笔為你收集整理的linux创建进程fork函数和vfork函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: “科学学”视角下的科研工作者行为研究
- 下一篇: BDTC 2017 | 中国大数据技术大