就是调用系统的程序,自定义的脚本不知为何有时不行。。自定义二进制文件却可以。

1.execl    list 列出参数列表

/*execl l是list 参数列表*/ #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> int main(){ pid_t result=fork(); int newret; if(result==-1){ perror("创建子进程失败!"); exit(0); }else if(result==0){ printf("返回值:%d,说明这是子进程!\n",result); printf("此进程的进程号(PID)是:%d \n",getpid()); printf("此进程的父进程号(PPID)是:%d\n",getppid()); //ls命令就放在/bin下 execl("/bin/ls","ls","-l",0);/*调用ls程序,显示当前目录下的文件信息*/ }else{ sleep(2);//等子进程 打印输出可能很慢 printf("返回值:%d,说明这是父进程!\n",result); printf("此进程的进程号(PID)是:%d \n",getpid()); printf("此进程的父进程号(PPID)是:%d\n",getppid()); } return 0; }

运行结果:

linux exec函数族演示_linux

 

2.execv  v:vector 给出参数列表数组

#include<stdio.h> #include<unistd.h> int main(){ //execl("/home/hanzhuan/.mycommand/a","a",NULL);//ok /* 不知为何 自己写的shell脚本不行 c编译和的二进制程序可以 */ /*char *const myhelp_args[]={"myhelp","calc",NULL}; execv("/home/hanzhuan/.mycommand/myhelp",myhelp_args);*/ char *const ps_argv[]={"ps","-o","pid,ppid,pgrp,session,tpgid,comm",NULL}; execv("/bin/ps",ps_argv); return 0; }

运行结果:

linux exec函数族演示_父进程_02

 

3.execle   le:list&enviroment 给出参数列表和环境变量数组

#include<stdio.h> int main(){ char *const ps_envp[]={"PATH=/bin:/usr/bin","TERM=console",NULL}; execle("/bin/ps","ps","-o","pid,ppid,pgrp,session,tpgid,comm",NULL,ps_envp); return 0; }

linux exec函数族演示_#include_03

 

4。execve  ve:vector&enviroment  给出参数数组和环境变量数组  最方便 也是系统唯一实现的一个函数 其他的都是调用此函数

/*最终都会调用这个函数*/ #include<stdio.h> int main(){ char *const ps_argv[]={"ps","-o","pid,ppid,pgrp,session,tpgid,comm",NULL}; char *const ps_envp[]={"PATH=/bin:/usr/bin","TERM=console",NULL}; execve("/bin/ps",ps_argv,ps_envp); return 0; }

linux exec函数族演示_#include_04

5.execlp  lp:list&path 不用给出具体路径(会自动查找) 给出参数列表

/*p:path 自动寻找路径*/ #include<stdio.h> #include<unistd.h> int main(){ //路径直接写个简单的”ps“就行了 会自动找到 execlp("ps","ps","-o","pid,ppid,pgrp,session,tpgid,comm",NULL); return 0; }

运行结果:

linux exec函数族演示_linux_05

 

6.execvp  vp:vector&path  不用给出具体路径  给出参数列表数组  (另一个ps也写在参数数组里)

/*execvp最是方便*/ #include<stdio.h> #include<unistd.h> int main(){ char *const ps_argv[]={"ps","-o","pid,ppid,pgrp,session,tpgid,comm",NULL}; execvp("ps",ps_argv); return 0; }

linux exec函数族演示_exec函数族_06