进程终止
进程终止是指一个正在运行的进程结束其执行并释放占用的系统资源的过程。进程可以通过以下几种方式终止:
在进程终止时,操作系统会回收已分配给该进程的内存空间、文件描述符、打开的文件等资源,并将进程的退出状态返回给父进程。
自定义退出码
enum{
success=0,
open_err,
malloc_err
};
const char* errorToDesc(int code)
{
switch(code)
{
case success:
return "success";
case open_err:
return "file open error";
case malloc_err:
return "malloc error";
default:
return "unknown error";
}
}
int Print()
{
printf("hello Linux\n");
printf("hello Linux\n");
printf("hello Linux\n");
printf("hello Linux\n");
return 0;
}
int main()
{
int n=Print();
printf("n=%d\n",n);
int code=malloc_err;
printf("%s\n",errorToDesc(code));
return 0;
}
打印出退出码表示的含义
exit()和_exit()
exit()和_exit()都是用于正常终止进程的函数
进程等待
进程等待指的是一个进程暂停其执行,直到满足某个条件或事件发生后才会继续执行。在操作系统中,进程可以通过等待来同步和协调与其他进程的操作。
wait
在Linux中,wait()是一个系统调用,是父进程在等待子进程执行完毕之前挂起自身,并等待子进程的终止状态。
父进程可以使用wait()等待子进程的终止。当父进程调用wait()时,如果子进程已经终止,则父进程会立即返回,并可以通过子进程的终止状态来了解子进程终止的 原因和状态。
下面来看例子:
waitpid()
waitpid()是Linux中的一个系统调用,用于等待指定子进程的终止并获取其终止状态。它可以用来在父进程中等待一个特定的子进程或者等待任何子进程的终止。
waitpid()函数的原型如下:
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *status, int options);
例子:
WIFEIERED
非阻塞等待
进程替换
进程替换是指在操作系统中将一个正在运行的进程替换为一个新的进程的过程。这个过程包括终止当前进程并加载新的程序代码、数据和资源,使新的进程开始执行。
在Linux中,常用exec()函数族来实现。
包括:
#include <unistd.h>`
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[]);
命名理解:
接下来看它们的使用
多进程替换