Linux进程替换(exec系列)

1、进程创建的原理(Linux上的):

bash:命令解释器

2、exec系列

(1)execl

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
 {
   printf("main pid=%d
",getpid());
   execl("/usr/bin/ps","ps","-f",(char*)0);

   printf("execl erroe
");
   exit(0);
}

注意:就是原来的程序换成了ps程序,但是PCB没有改变,但是PCB里面的有些值被修改 了,比如pcb中程序的名字换成了新进程的名字;

注意,"abc"可以, "/usr/bin/psxx"不可以;,如下:

(2)execlp

只给文件名,不需要给文件路径,可以去环境变量PATH所指的位置去搜索

echo $PATH

(3)execle

execle多了一个环境变量

(4)execv

execv系列把参数都放在一个数组中,把这个数组传递进去即可。

(5)execvp

第一个参数只要文件名,不要路径

(6)execve系统调用

本质上,前面5个都是调用的这个系统调用execve

(7)总结替换方法

man execl看帮助手册
//path:新替换的程序的路径名称
//arg :传给新程序主函数的第一个参数,一般为程序的名字
//arg 后面是剩余参数列表,参数个数可变,必须以空指针作为最后一个参数

int execl(const char* path, const char * arg,...);

int execlp(const char* file, const char * arg,...);//在环境变量PATH
指定的路径里面搜索;

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 * path, char* const argv[],char* const envp[]); //系统调用

//前五个是库函数,最后一个是系统调用,所以本质上上面5个都是通过第六个系统调用实现
的.

3、fork+exec()

例一:

利用bash创建ps命令----execl的使用(结合fork)

fork+exec()是Linux上创建新进程方式;

当前主程序复制产生一个子进程,子进程用程序ps替换自身;

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/wait.h>
int main()
{
printf("main pid=%d,ppid=%d
",getpid(),getppid());
pid_t pid=fork();
assert(pid!=-1);
if(pid==0)
{
printf("child pid=%d,ppid=%d
",getpid(),getppid());
execl("/usr/bin/ps","ps","-f",NULL);
printf("execl error");
exit(0);
}
wait(NULL);
exit(0);
}

例二:

当前主程序复制产生一个子进程,子进程用新程序“b”替换自身;

//test.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/wait.h>
#include <errno.h>
int main(int argc,char *argv[],char *envp[])
{
printf("main pid=%d
",getpid());
pid_t pid=fork();
assert(pid!=-1);
if(pid==0)
{
char *myargv[]={"b","hello","abc","123",(char *)0};
execve("./b",myargv,envp);
perror("execve error");
exit(0);
}
wait(NULL);
printf("main over!
");
exit(0);
}

//b.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>

int main(int argc,char *argv[],char *envp[])
{
printf("b pid=%d
",getpid());
int i=0;
printf("argc=%d
",argc);
for(;i<argc;i++)
{
printf("argv[%d]=%s
",i,argv[i]);
}
for(i=0;envp[i]!=NULL;i++)
{
printf("envp[%d]=%s
",i,envp[i]);
}
exit(0);
}
经验分享 程序员 微信小程序 职场和发展