子进程的环境变量问题

来源:互联网 发布:midi 入门 软件 编辑:程序博客网 时间:2024/06/07 08:38
1.我在做项目的时候遇到一个问题:
C程序使用execle调用了一个脚本并用环境变量的方式给他传参,然后这个脚本需要再去调用另一个脚本,我写了一个程序来测试后面被调用的脚本
有没有在使用这个环境变量

基础知识:
execle(const char *path, const char *arg, ..., char * const envp[])
参数:
path参数表示你要启动程序的名称包括路径名
arg参数表示启动程序所带的参数,一般第一个参数为要执行命令名,不是带路径且arg必须以NULL结束
返回值:成功返回0,失败返回-1
//main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(void)
{
char *path=(void *) malloc(64);
memset(path,0,64);
char *t_path="/home/aston/my_shell/sh_env/give_env.sh";
memcpy(path,t_path,strlen(t_path));
char *proce="env=hello";
char *name="env2=world";
char ** tmp_env;
tmp_env=(void *)malloc(64);
tmp_env[0]=proce;
tmp_env[1]=name;
int ret=0;
if(execle(path ,path, NULL, tmp_env) < 0)
printf("errno=%s\n", strerror(errno));
/*这里与上面是相同的结果,没有必要去申请一段新的内存
if(execle(t_path ,t_path, NULL, tmp_env) < 0)
printf("errno=%s\n", strerror(errno));
*/
free(path);
free(tmp_env);
return 0;
}


//give_env.sh
#!/bin/sh
echo "1=$1,2=$2"
echo "give $env,$env2"
./print_env.sh $env $env2


//print_env.sh
#!/bin/sh
echo '$1='$1
echo env=$env
echo env2=$env2
echo env3=$env3
echo env_test=$env_test




运行结果:
1=,2=
give hello,world
$1=hello
env=hello
env2=world

结论:子进程是继承了父进程的环境变量(这个很多将进程的地方都有提到),而且脚本调用新的脚本,也会和旧的脚本共享环境变量!





原创粉丝点击