fork vs vfork
1. 成功调用一次,返回两个值,子进程返回0,父进程返回子进程的pid;出错返回-1
2. 头文件:
#include <unistd.h>
#include <sys/types.h>
3. fork函数会拷贝父进程的数据空间、堆栈等资源,这样就会有两份数据,与父进程不相干扰。
4. vfork函数不会拷贝父进程的资源,与父进程公用一份资源,修改数据会影响到父进程的数据一致性。
5. 使用exec切换到新的程序或者使用exit退出。
6. 当调用vfork函数去创建子进程的时候,需要使用_exit()退出,因为_exit()退出时,不会清除缓存区和关闭所有文件,若使用exit()退出则会严重影响父进程
Example:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
void main(){
pid_t pid;
if(fork() == 0){ //子进程中
printf("In child process, pid is %d\n", getpid());
exit(0);
}
else{ //父进程中
printf("In parent process, pid is %d\n", getpid());
}
}
http://baike.baidu.com/view/1952900.htm
http://baike.baidu.com/view/1745340.htm
exit() vs _exit()
1. exit(0) 表示正常退出,exit(xx) xx非0则为异常退出
2. exit() 函数会直接退出程序,即便是在被调用的函数的外部函数执行;
3. _exit() 直接使进程停止运行,清除其所使用的内存空间,并销毁其在内核中的各种数据结构,exit()在调用exit系统调用之前要检查文件的打开情况,把文件缓冲区的内容写回文件。
#include <stdio.h>
#include <stdlib.h>
void main(){
int i;
for(i = 0; i < 3; i++){
printf("%i\n", i);
}
void func();
func();
// exit(0);
printf("?????\n"); //不会被输出
}
void func(){
printf("In func\n");
exit(0);
}
http://baike.baidu.com/view/1542946.htm