前言
继续学习Linux进程!
目录
2.vfork()保证子进程先运行,当子进程调用exit()退出后,父进程才执行
提示:以下是本篇文章正文内容,下面案例可供参考
一、创建进程
1.fork()函数创建进程
1.1 函数原型:
#include <unistd.h>
pid_t fork(void);
/*fork()函数调用成功,返回两次
返回 0 代表当前进程是子进程
返回非负数 代表当前进程是父进程
调用失败 返回-1
1.2 代码示例:
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
int cnt = 0;
pid = fork();
if(pid > 0){
printf("this is father pid = %d \n",getpid());
}else if(pid == 0){
printf("this is person pid,person pid=%d\n",getpid());
}
return 0;
}
~
~
1.3 运行结果:
2.vfork()函数创建进程
2.1 函数原型:
#include <sys/types.h>
#include <unistd.h>
pid_t vfork(void);
2.2 代码示例:
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
int cnt = 0;
pid = vfork();
if(pid > 0){
while(1){
printf("this is father pid = %d \n",getpid());
sleep(2);
}
}else if(pid == 0){
while(1){
printf("this is person pid,person pid=%d\n",getpid());
sleep(2);
cnt++;
if(cnt == 3){
exit(0);
}
}
}
return 0;
}
~
~
2.3 运行结果:
二、fork()函数与vfork()函数的区别
1.vfork()函数直接父进程存储空间,不拷贝
2.vfork()保证子进程先运行,当子进程调用exit()退出后,父进程才执行
3.fork()函数父进程和子进程都要运行
4.fork()子进程拷贝父进程内存空间
总结
理解进程的创建,fork()函数和vfork()函数,下一个博客总结学习进程的退出。