一、fork函数
(一)fork函数头文件
#include <sys/types.h>
#include <unistd.h>
(二)fork函数原型
pid_t fork(void);
(三)fork函数的作用
通过复制正在调用的进程来创建一个新的进程,这个新的进程被称为子进程。
(四)返回值
父进程:返回子进程id
子进程:返回0
错误:返回-1
(五)用法展示
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid = fork();//创建子进程
if(pid == -1)
{
perror("fork");
return -1;
} //判断是否创建成功
if(pid == 0) //返回0则为子进程
{
printf("the child id is:%d,the parent id is:%d\n",getpid(),getppid());
}
else //否则为父进程
{
printf("the parent id is:%d,my parent id is:%d",getpid(),getppid());
}
return 0;
}
二、vfork函数
(一)vfork函数头文件
#include <sys/types.h>
#include <unistd.h>
(二)vfork函数原型
pid_t vfork(void);
(三)vfork函数的作用
vfork函数拥有跟fork函数一样用于创建子进程的作用,但是vfork并不拷贝父进程的叶表
(四)返回值
父进程:返回子进程id
子进程:返回0
错误:返回-1
(五)用法展示
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid = vfork();//创建子进程
if(pid == -1)
{
perror("vfork");
return -1;
} //判断是否创建成功
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid = fork();//创建子进程
if(pid == -1)
{
perror("fork");
return -1;
} //判断是否创建成功
if(pid == 0) //返回0则为子进程
{
printf("the child id is:%d,the parent id is:%d\n",getpid(),getppid());
}
else //否则为父进程
{
printf("the parent id is:%d,my parent id is:%d",getpid(),getppid());
}
return 0;
}
return 0;
}
(三)区别
vfork不将父进程中的地址空间完全复制到子进程,仅与父进程共享数据段,fork函数父子进程的运行次序是不确定的,而vfork函数保证了子进程先运行,在调用exec 或exit 之前与父进程数据是共享的,在它调用exec或exit 之后父进程才可能被调度运行。如果在调用这两个函数之前子进程依赖于父进程的进一步动作,则会导致死锁。