注:Linux进程 11
一、exec()函数
// int execlp(const char *file, const char *arg, …);
// int execl(const char *path, const char *arg, …);
// int execv(const char *path, char *const argv[]);
// int execvp(const char *file, char *const argv[]);
- execl()
- execlp()
- execvp
- execv
二、代码
1.execl()
code:seek.c
指令:gcc seek.c -o one
#include <stdio.h>
#include <unistd.h>
int main(int agrc,char **agrv)
{
int i=0;
for(i=0;i<agrc;i++){
printf("agrv[%d]=%s\n",i,agrv[i]);
}
return 0;
}
code:demonew18.c
CLC@Embed_Learn:~/LinuxLearn/PID$ cat demonew18.c
#include <stdio.h>
#include <unistd.h>
// int execl(const char *path, const char *arg, ...);
int main()
{
printf("execl funtion before\n");
//****若不加NULL,ERROR。
if(execl("./one","./one","aa","bb",NULL) == -1){
printf("Not Find File\n");
perror("ERROR Reason:");
}
printf("SEEK!!!\n");
return 0;
}
执行的结果:
CLC@Embed_Learn:~/LinuxLearn/PID$ ./a.out
execl funtion before
agrv[0]=./one
agrv[1]=aa
agrv[2]=bb
CLC@Embed_Learn:~/LinuxLearn/PID$ ./one aa bb
agrv[0]=./one
agrv[1]=aa
agrv[2]=bb
CLC@Embed_Learn:~/LinuxLearn/PID$ ./a.out
execl funtion before
agrv[0]=./one
agrv[1]=aa
agrv[2]=bb
CLC@Embed_Learn:~/LinuxLearn/PID$ ./one aa bb
agrv[0]=./one
agrv[1]=aa
agrv[2]=bb
code:demo19.c( 利用exec执行(ls -l 或者 ps))
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("execl funtion before\n");
if(execl("/bin/ls","ls","-l",NULL) == -1){
printf("Not Find File\n");
perror("ERROR Reason:");
}
/* if(execl("/bin/ps","ps",NULL) == -1){
printf("Not Find File\n");
perror("ERROR Reason:");
}*/
printf("SEEK!!!\n");
return 0;
}
2.execlp()
代码:
#include <stdio.h>
#include <unistd.h>
// int execlp(const char *file, const char *arg, ...);
// int execl(const char *path, const char *arg, ...);
int main()
{
printf("NOW TIME:\n");
if(execlp("date","date",NULL) == -1){
printf("Not Find File\n");
perror("ERROR Reason:");
}
printf("SEEK!!!\n");
return 0;
}
3.execvp
代码:
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("NOW TIME:\n");
char *argv[]={"data",NULL};
if(execvp("date",argv) == -1){
printf("Not Find File\n");
perror("ERROR Reason:");
}
printf("SEEK!!!\n");
return 0;
}
4.execv()
代码:
#include <stdio.h>
#include <unistd.h>
// int execv(const char *path, char *const argv[]);
// int execvp(const char *file, char *const argv[]);
int main()
{
printf("NOW TIME:\n");
char *argv[]={"data",NULL};
if(execv("/bin/date",argv) == -1){
printf("Not Find File\n");
perror("ERROR Reason:");
}
printf("SEEK!!!\n");
return 0;
}
三、小结
它们之间的区别在于const char *file
和const char *path
。path需要找到文件所在的绝对路径,而file不需要。
指令:
- echo $PATH //当前环境变量
- whereis ls //找到ls的绝对路径
- cd - // 返回上一次路径