#Linux系统编程(exec函数族)

(一)发行版:Ubuntu16.04.7


(二)记录:

(1)为什么介绍exec函数族

在父进程fork()创建子进程中,子进程会拷贝父进程的代码,但是有时候不想要子进程拷贝父进程的代码,则需要引入exec函数族。

(2)exec函数原型

在Linux中并没有exec函数,而是有6个以exec开头的函数族,下面列举了exec函数族的6个函数成员的函数原型:

(3)exec函数族能够更换程序的原因

“换核不换壳”,exec不换创建新进程,但是会换进程里面的执行代码。

(4)调用exec函数族的情况

a.当进程认为自己不能再为系统和用户做出任何贡献时,就可以调用任何exec函数让自己重生。

b.如果一个进程想执行另一个程序,那么他就可以调用fork函数新建一个进程,然后调用一个exec函数使子进程重生。

(5)使用execl换核

a.创建一个c文件,编译生成可执行文件(即图中hello 会打印hello world.)

b.在上篇文章代码基础上增加

    //子进程
	if(pid==0)
	  {
		execl("/home/samba/process/hello","hello",NULL);
	    exit(1);       
	//	printf("This is a child process,child_pid: %d\nparent_pid: %d\n",getpid(),getppid());
	  }

在子进程中增加execl函数换核,第一个参数为可执行文件的绝对路径,第二个参数可执行文件的名字。 

c.编译运行

(6)换核换自有的命令

    //子进程
	if(pid==0)
	  {
	//	execl("/home/samba/process/hello","hello",NULL);
        execl("/bin/ls","ls","-al",NULL);
	    exit(1);       
	//	printf("This is a child process,child_pid: %d\nparent_pid: %d\n",getpid(),getppid());
	  }

 -al为传给ls的命令


(三)命令:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
	pid_t pid;
	pid=fork();
	if(pid<0){
		printf("fork is error.\n");
		return -1;
	}

	//父进程
	if(pid>0)
		printf("This is a parent process,parent_pid: %d\n",getpid());
    //子进程
	if(pid==0)
	  {
	//	execl("/home/samba/process/hello","hello",NULL);
        execl("/bin/ls","ls","-alh",NULL);
	    exit(1);       
	//	printf("This is a child process,child_pid: %d\nparent_pid: %d\n",getpid(),getppid());
	  }
	return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值