exec系列函数(待续)

一、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 函数


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值