【Linux】进程—创建进程

前言

继续学习Linux进程!

目录

前言

一、创建进程

1.fork()函数创建进程

1.1 函数原型:

1.2 代码示例:

1.3 运行结果:

 2.vfork()函数创建进程

 2.1 函数原型:

 2.2 代码示例: 

 2.3 运行结果: 

二、fork()函数与vfork()函数的区别

1.vfork()函数直接父进程存储空间,不拷贝

2.vfork()保证子进程先运行,当子进程调用exit()退出后,父进程才执行

3.fork()函数父进程和子进程都要运行

4.fork()子进程拷贝父进程内存空间

总结


提示:以下是本篇文章正文内容,下面案例可供参考

一、创建进程

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()函数,下一个博客总结学习进程的退出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星筠君辰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值