linux系统exec族函数

exec族函数函数的作用:

我们用fork函数创建新进程后,经常会在新进程中调用exec函数去执行另外一个程序。当进程调用exec函数时,该进程被完全替换为新程序。因为调用exec函数并不创建新进程,所以前后进程的pid并没有改变。

功能:
  在调用进程内部执行一个可执行文件。可执行文件既可以是二进制文件,也可以是任何Linux下可执行的脚本文件。
函数族:
  exec函数族分别是:execl, execlp, execle, execv, execvp, execvpe

返回值:
  exec函数族的函数执行成功后不会返回,调用失败时,会设置errno并返回-1,然后从原程序的调用点接着往下执行。

例子说明:

1.execl()函数

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>

int main()
{
        printf("before execl\n");
        if(execl("/bin/ls","ls","-l",NULL)== -1)
//调用 bin路径下的ls 生成的可执行文件 就是ls的功能后面加名字 后面再加-l就是增加功能
        {
                printf("execl failed\n");
                perror("why");
        }
        printf("after execl\n");
        return 0;

}

实现ls -l功能  因为加上路径

2.execlp()函数 无视路径  

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>

int main()
{
        printf("before execl\n");
        if(execlp("ls","ls","-l",NULL)== -1)
        {
                printf("execl failed\n");
                perror("why");
        }
        printf("after execl\n");
        return 0;

}

3.execv()函数  实现ls -l功能

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>

int main()
{
        printf("before execl\n");

        char *argv[] = {"ls","-l",NULL,NULL};

        if(execv("/bin/ls",argv)==-1)          //相当于ls,ls,NULL,NULL
        {
                printf("execl failed\n");
                perror("why");
        }
        printf("after execl\n");
        return 0;
}

4.execvp()函数 无视路径

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>

int main()
{
        printf("before execl\n");

        char *argv[] = {"ls",NULL,NULL};

        if(execvp("ls",argv)==-1)          //相当于ls,ls,NULL,NULL
        {
                printf("execl failed\n");
                perror("why");
        }
        printf("after execl\n");
        return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值