文章目录
exec进程替换
一.exec系列
1.execl
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
printf("main pid=%d\n",getpid());
execl("/usr/bin/ps","ps","-f",(char*)0);
printf("execl error\n");
exit(0);
}
注意,就是原来的程序换成了ps程序,但是PCB没有改变,但是PCB里面的有些值被修改了,比如pcb中程序的名字换成了新进程的名字;
2.execlp
只给文件名,不需要给文件路径,可以去环境变量PATH所指的位置去搜索;
echo $PATH
3.execle
这个execle多了一个环境变量;
4.execv
execv系列把参数都放在了一个数组中,然后把这个数组传递进去即可;
5.execvp
第一个参数只要文件名,不要路径;
6.execve系统调用
本质上,前面5个都是调用的这个系统调用``execve;
7.总结替换方法:
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 * path, char* const argv[],char* constenvp[]); //系统调用
二.fork+exec()例子
1.利用bash创建ps命令----execl的使用结合(结合fork)
fork+exec()是Linux上创建新的进程的方式
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<assert.h>
#include<sys/wait.h>
int main()
{
printf("main pid=%d,ppid=%d\n",getpid(),getppid());
pid_t pid=fork();
assert(pid!=-1);
if(pid==0)
{
printf("child pid=%d,ppid=%d\n",getpid(),getppid());
execl("/usr/bin/ps","ps","-f",NULL);
printf("execl error");
exit(0);
}
wait(NULL);
exit(0);
}
2.当主程序复制产生一个子进程,子进程用新程序(b)替换自身
代码test.c
#include<stdio.h>
#include<assert.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main(int argc,char *argv[],char *envp[])
{
printf("main pid=%d\n",getpid());
pid_t pid=fork();
assert(pid!=-1);
if(pid==0)
{
char *myargv[]={"b","hello","abc","123",(char*)0};
execve("./b",myargv,envp);
perror("execl error");
exit(0);
}
wait(NULL);
printf("main over\n");
exit(0);
}
代码:b.c
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
int main(int argc,char *argv[],char *envp[])
{
printf(" b pid=%d\n",getpid());
int i=0;
printf("argc=%d\n",argc);
for(i=0;i<argc;i++)
{
printf("argv[%d]=%s\n",i,argv[i]);
}
for(i=0;envp[i]!=NULL;i++)
{
printf("envp[%d]=%s\n",i,envp[i]);
}
exit(0);
}