Linux C编程——execve总结

本文介绍了execve函数的作用及使用方法,通过两个实例演示了如何利用execve调用可执行程序和shell脚本,并展示了如何传递参数和环境变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

execve函数作用是执行一个新的程序,程序可以是二进制的可执行程序,也可以是shell、pathon脚本

函数原型:

int execve(const char * filename,char * const argv[ ],char * const envp[ ]);

参数介绍:

filename:程序所在的路径

argv:传递给程序的参数,数组指针argv必须以程序(filename)开头,NULL结尾

envp:传递给程序的新环境变量,无论是shell脚本,还是可执行文件都可以使用此环境变量,必须以NULL结尾

函数返回值:

成功无返回值,失败返回-1

例子1,调用可执行程序

main.c---->main程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
    char *envp[] = {"T1=222","T2=333",NULL};
    char *argv_send[] = {"./execve_test","1","2",NULL};
    execve("./execve_test",argv_send,envp);

    printf("do this.....\r\n");
    return 0;
}

execve_test.c---->execve_test程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
extern char **environ;
int main(int argc, char *argv[])
{
    int i = 0;
    //打印envp,新环境变量
    for( i = 0; environ[i] != NULL; i++ )
    {
        printf("environ[%d]:%s\r\n",i,environ[i]);
    }

    printf("\r\n\r\n");

    //打印argv,参数
    for( i = 0; i < argc; i++ )
    {
        printf("argv[%d]:%s\r\n",i,argv[i]);
    }
    return 0;
}

执行程序:./main

执行结果:

environ[0]:T1=222
environ[1]:T2=333

argv[0]:./execve_test
argv[1]:1
argv[2]:2


例子2,调用shell脚本

main.c---->main程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
    char *envp[] = {"T1=222","T2=333",NULL};
    char *argv_send[] = {"./execve_shell.sh","1","2",NULL};
    execve("./execve_shell.sh",argv_send,envp);

    printf("do this.....\r\n");
    return 0;
}

execve_shell.sh脚本

#!/bin/bash
echo $0 $1 $2
echo $T1
echo $T2

执行程序:./main

执行结果:

./execve_shell.sh 1 2
222
333

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值