1.创建进程
linux下创建进程有两种方式即调用fork函数或者vfork函数
//头文件
#include<unistd.h>
1.1 fork()
pid_t fork(void);
//返回值为0 --- 子进程
//返回值为-1 --- 创建失败
//返回值为pid --- 父进程
1.2 vfork()
pid_t vfork(void);
注意:vfork与父进程共有同一块虚拟地址空间,而fork的虚拟地址空间独立。
2.进程终止
2.1 exit()
exit()是库函数,退出前会刷新缓冲区 ,做了一系列收尾操作后释放资源
#inldue<unistd.h> //头文件
函数接口:
void _exit(int status);
我们可以用如下的demo观察,exit的作用
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("hello world");
sleep(3);
exit(0);
return 0;
}
//运行结果:程序正常退出并且打印语句
2.2 _exit()
_eixt() 是系统调用 直接释放资源退出进程
#include<unistd.h>
函数接口
void _exit(int status);
我们同样用一个demo,体会_exit的作用
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("hello world");
sleep(3);
_exit(0);
return 0;
}
//运行结果,sleep三秒之后直接退出。
3.进程等待
3.1 wait()
//头文件
#include <sys/types.h>
#include <sys/wait.h>
函数接口:
pid_t wait(int *status);
//成功则返回等待进程的pid 失败返回-1
我们通过,以下demo来体会wait的作用
int main()
{
int pid = fork();
if(pid < 0){
perror("fork error");
exit(-1);
}else if(pid == 0){
sleep(3);
exit(0);
}
int status;
int ret = wait(&status);
printf("%d ---- %d",pid,ret);
while(1){
printf("---------------\n");
sleep(1);
}
return 0;
}
在子进程里,无论这个sleep时间给多久,我们都可以通过返回值看到接受的进程pid,这也即是wait的特点,无则阻塞。
3.2 waitpid()
pid_t waitpid(pid_t pid, int *status, int options);
参数:
-
pid
pid = -1,等待任意一个子进程 --- 与wait等效 pid > 0 等待进程id与pid相等的子进程
-
status
WIFEXITED(status):查看进程退出是否退出正常 WEXITSTATUS(status):查看进程的退出码
-
options
WNOHANG:设置非阻塞
waitpid较于wait最大区别在于,前者可以设置非阻塞状态,即如果pid指定的子进程没有结束退出,那么waitpid不会等待。
4.进程替换
首先我们来看exece函数族
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg,
..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *file, char *const argv[],
char *const envp[]);
上面六个函数本质上,最终都调用的是execve这个系统调用函数,在以上函数里
l表示参数用列表,v代表参数用vector,p代表默认环境变量,e代表手动维护环境变量。
例如我们这里用其中的两个作为展示
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
printf("hello\n");
execlp("ls","ls","-l",NULL);
// execl("/bin/ls","ls","-l",NULL);
return 0;
}