您的位置:首页 > 其它

exec系列函数(待续)

2016-07-31 13:48 155 查看






一、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 process
i am dead
welcome a new place
a
b
c


单独运行 a 

xfliu@ubuntu:exec函数$ ./bin/a a b c
welcome a new place
./bin/a
a
b
c


对比一下结果

调用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 process i am dead welcome a new place a b c

三、execle 函数

四、execve 函数

五、execlp 函数

六、execvp 函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: