exec函数用法

1、execl

//文件execl.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);

int main(void)
{
    printf("before execl\n");
    if(execl("./bin/echoarg","echoarg","abc",NULL) == -1)        //第一个参数为可执行程序的路径名字,第二个为参数列表,必须以NULL结尾,第三个参数是执行gcc echoarg.c时在在后面加的需要执行的文件名。
    {
        printf("execl failed!\n");      
    }
    printf("after execl\n");
    return 0;
}

2、execlp

加环境变量命令:export PATH=$PATH:(需要加到的目标路径)

加环境变量的意思是即是要执行的程序不在当前文件夹,只需要添加环境变量到需要执行的程序的路径,即可在其他路径也能执行需要执行的程序。

//文件execl_no_path.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
    printf("before execl****\n");
    if(execl("ps","ps","-l",NULL) == -1)
    {
        printf("execl failed!\n");
    }   
    printf("after execl*****\n");
    return 0;
}

3、execvp

//文件execvp.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execvp(const char *file, char *const argv[]);

int main(void)
{
    printf("before execlp****\n");
    char *argv[] = {"ps","-l",NULL};
    if(execvp("ps",argv) == -1) 
    {
        printf("execvp failed!\n");     
    }
    printf("after execlp*****\n");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值