Linux系统编程-进程-exec函数族

119 阅读2分钟

为什么叫函数族,因为有一堆名字差不多,然后效果差不多的函数
为什么叫exec,因为他可以直接调用可执行文件,而不需要自己再写一份代码

exec函数族原理: fork原理上,子进程复制父进程,但是调用exec后,子进程内容清空,覆盖为exec指定的可执行程序,就是直接被夺舍了。

主要掌握execl和execlp

execl函数

int execl(const char* path, const char* arg, ...)

参数:

  • path:可执行文件的路径
  • const char* args, ... : 命令

返回值:

  • 成功:无返回
  • 失败:-1

execlp函数

int execlp(const char* path, const char* arg, ...) 参数:

  • path:环境变量PATH里的可执行文件
  • const char* args, ... : 命令

返回值:

  • 成功:无返回
  • 失败:-1

示例

execlp("ls","ls","-l",NULL);
execl("/bin/ls","ls","-l",NULL);

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc,char* argv[]){
	pid_t pid=fork();
	if(pid==-1){
		perror("fork error");
		exit(1);
	}else if(pid==0){  //子进程
		//如果想要执行自己的可执行程序,就用execl
		//参数依然是可执行文件路径,然后命令
		execl("a.out","./a.out",NULL);
	}else if(pid>0){  //父进程
		printf("I'm parent : %d\n",getpid());
	}
	return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc,char* argv[]){
	pid_t pid=fork();
	if(pid==-1){
		perror("fork error");
		exit(1);
	}else if(pid==0){  //子进程
		//这里的p的意思是PATH,因为bash解释命令的的时候是到环境变量PATH里面去可执行文件
		//先输入可执行文件名,然后是命令,用NULL是哨兵,表示命令的结束
		execlp("ls","ls","-l","-h",NULL);
	}else if(pid>0){  //父进程
		printf("I'm parent : %d\n",getpid());
	}
	return 0;
}
//实现ps -ax > ps.out
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc,char* argv[]){
	int fd;
	fd=open("ps.out",O_RDWR|O_CREAT,0644);
	if(fd<0){
		perror("open ps.out error");
		exit(1);
	}

	dup2(fd,STDOUT_FILENO);
	
	execlp("ps","ps","-ax",NULL);
	close(fd);
	return 0;
}