exec系列函数(待续)

来源:互联网 发布:java项目并发量 编辑:程序博客网 时间:2024/05/22 09:07

一、execl 函数

#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<stdlib.h>#include <sys/stat.h>#include <fcntl.h>#include <string.h>void getPath(char *path){char link[100];    sprintf( link, "/proc/%d/exe", getpid() );     int i = readlink( link, path, 100 );    while(*(path+i)!='/'){    *(path+i)='\0';    --i;    }}int main(void){pid_t pid=fork();int n=0;int i=0;char *s=NULL;char path1[500]="\0";if(pid<0){perror("fork creat ");}else if(pid>0){//父进程s="this is parent process";}else{//pid=0//子进程s="this is child process";char Path[100]="\0";getPath(Path);strcat(Path,"a");//printf("%s\n",Path);execl(Path,"a","b","c",NULL);}printf("%s\n",s);printf("i am dead\n");sleep(1);return 0;}


另一个新进程

#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<stdlib.h>int main(int argc,char *argv[]){printf("welcome a new place\n");for(int i=0;i<argc;++i){printf("%s\n",argv[i]);}return 0;}

运行结果


this is parent processi am deadwelcome a new placeabc

单独运行 a 

xfliu@ubuntu:exec函数$ ./bin/a a b cwelcome a new place./bin/aabc

对比一下结果

调用execl 函数时,命令行变量采集执行文件路径不算了

二、execlv 函数

#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<stdlib.h>#include <sys/stat.h>#include <fcntl.h>#include <string.h>void getPath(char *path){char link[100];    sprintf( link, "/proc/%d/exe", getpid() );     int i = readlink( link, path, 100 );    while(*(path+i)!='/'){    *(path+i)='\0';    --i;    }}int main(void){pid_t pid=fork();int n=0;int i=0;char *s=NULL;char path1[500]="\0";char *arg[5];arg[0]="a";arg[1]="b";arg[2]="c";if(pid<0){perror("fork creat ");}else if(pid>0){//父进程s="this is parent process";}else{//pid=0//子进程s="this is child process";char Path[100]="\0";getPath(Path);strcat(Path,"a");execv(Path,arg);//传递二维数组}printf("%s\n",s);printf("i am dead\n");sleep(1);return 0;}


运行结果:

this is parent processi am deadwelcome a new placeabc



三、execle 函数



四、execve 函数

五、execlp 函数

六、execvp 函数


0 0
原创粉丝点击