学习目标:
一、概述
二、fork
三、exec函数族
四、wait函数族
五、总结
学习内容:
可借鉴:
https://blog.csdn.net/qq_45824568/article/details/115224295?spm=1001.2014.3001.5501
一、
1、抢占式VS非抢占式(并发VS并行)
getpid:获取当前进程号
getppid:获取当前父进程号
二、
1、获取ID:
#include <sys/types.h>
#include <unistd.h>
pid_t getpid(void); //pid_t 表示进程id类型
//获取本进程ID
pid_t getppid(void);
//获取父进程ID
2、创建进程
#include <unistd.h>
pid_t fork(void);
//创建子进程
fork被调用一次返回两次,他可能有三种不同的返回值:
1.在父进程中fork返回新创建的子进程的PID。
2.在子进程中,fork返回0.
3. 如果出现错误,fork返回一个负值
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(void){
pid_t pid;
pid = fork();
if (pid < 0)
{
printf("error in fork!\n");
}
else (pid == 0)
{
printf("I am the child process,ID is %s\n",getpid());
}
else if
{
printf("I am the parent process,ID is %d\n",getpid());
}
return 0;
}
两个基本完全相同的进程,哪个进程先执行要看系统的进程调度策略
1·vfork:子进程与父进程共享数据段。
fork: 子进程拷贝父进程的数据段。
2·fork: 父,子进程的执行次序不确定。
vfork: 子进程先运行,父进程在运行
三条进程,ABC交替输出
#include"stdio.h"
#include"sys/types.h"
#include"unistd.h"
#include"stdlib.h"
int main()
{
int i=0;
for(i=0;i<5;i++)
{
pid_t pid =vfork();
if(-1 == pid)
{
perror("fprk error");
exit(1);
}
if(0 == pid)
{
printf("A\n");
exit(1);
}
else
{int pit =vfork();
if(-1 ==pit)
{
perror("fork error!");
exit(1);
}
if(0 == pit)
{
printf("B\n");
exit(1);
}
else
{
printf("C\n");
}
}
}
}
三、exec函数族
1、进程退出
(1)一般正常情况下退出:exit(0),异常情况退出exit(1).
(2)父进程可以使用return 0和exit(0)来退出,子进程只能使用exit(0),不能使用return 0来退出。
2、进程等待
3、exec
exec在替换了原有的进程之后,还是会使用调用它的子进程的pid。
该函数族如下:
(1)int execl(const char*path, const char *arg, ......);
(2)intexecle(const char *path, const char *arg, ...... , char * const envp[]);
(3)intexecv(const char *path, char *const argv[]);
(4)intexecve(const char *filename, char *const argv[], char *const envp[]);
(5)intexecvp(const char *file, char * const argv[]);
(6)intexeclp(const char *file, const char *arg, ......);
exec函数族装入并运行程序path/file,并将参数arg0(arg1, arg2,argv[], envp[])传递给子程序,出错返回-1.
在exec函数族中,后缀l、v、p、e指定函数将具有某种操作能力:
后缀 | 操作功能 |
---|---|
l | 希望接收以逗号分隔的参数列表,列表以NULL指针作为结束标志 |
v | 希望接收到一个以NULL结尾的字符串数组的指针 |
p | 是一个以NULL结尾的字符串数组指针,函数可以DOS的PATH变量查找子程序文件 |
e | 函数传递指定参数envp,允许改变子进程的环境,无后缀e时,子进程使用当前程序的环境 |
即调用进程内部执行一个可执行文件
四、wait函数族
僵尸进程
孤儿进程
五、总结
进程的优缺点
优点:
对用户来说,操作系统会变得更加健壮(一个进程无法破坏另一个进程或操作系统的运行)
对于开发者来说,更容易进行内存的读取和写入
缺点:
多任务实现开销比较大
编写能够与其他进程通信或者能够对其他进程操作的应用程序将要困难的多