🔥个人主页:guoguoqiang. 🔥专栏:Linux的学习
进程程序替换
替换函数
有六种以exec开头的函数,统称exec函数。
#include <stdio.h>
#include <unistd.h>
int main(){
printf("testexec ...begin!\n");
execl("/usr/bin/ls","ls","-a","-l",NULL);
printf("testexec ...end!\n");
return 0;
}
execl被ls替换了,替换也是完完全全的,不会执行后面的代码。
替换原理
用fork创建子进程后执行的是和父进程相同的程序(但有可能执行不同的代码分支),子进程往往要调用一种exec函数
以执行另一个程序。当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,从新程序的启动
例程开始执行。调用exec并不创建新进程,所以调用exec前后该进程的id并未改变。
站在被替换进程的角度:本质就是这个程序被加载到内存中了;通过exec*加载函数。
多进程替换
fork创建子进程,让自进程自己去替换
创建子进程的目的是让子进程完成任务:1.让子进程执行父进程代码的一部分 2.让子进程执行一个新的程序
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(){
printf("testexec ...begin!\n");
pid_t id=fork();
if(id==0){
printf("child pid: %d\n",getpid());
sleep(2);
execl("/usr/bin/ls","ls","-a","-l",NULL);
exit(1);
}
//father
int status=0;
pid_t rid=waitpid(id,&status,0);
if(rid>0){
printf("father wait success,child exit code :%d \n",WEXITSTATUS(status));
}
printf("testexec ...end!\n");
return