通过execve在两个进程间传递环境变量

来源:互联网 发布:网络平台营业执照 编辑:程序博客网 时间:2024/06/10 23:47

进程1:execve
进程2:hello

execve.h 的代码如下:

#include <stdio.h>#include <stdlib.h>#include <unistd.h>/*     #include <unistd.h>     execve是系统调用,下面的函数是execve的库函数     extern char **environ;     int execl(const char *path, const char *arg, ...);     int execlp(const char *file, const char *arg, ...);     int execle(const char *path, const char *arg,                ..., char * const envp[]);     int execv(const char *path, char *const argv[]);     int execvp(const char *file, char *const argv[]);*/int main(void){    printf("pid: %d\n", getpid());    // 自定义的环境变量参数列表---> 其实就是一个指针数组    char * const envp[] = {"aaa=111", "bbb=222", NULL};    execve("./hello", NULL, const);    printf("hello...\n");    return 0;}

hello.c的代码:

#include <stdio.h>#include <stdlib.h>#include <unistd.h>// environ:环境变量 ===== 指针数组extern char **environ;int main(void){    int i = 0;    printf("hello_pid: %d\n", getpid());    for (i = 0; environ[i] != NULL; i++) {        printf("%s\n", environ[i]);    }    return 0;}

单独执行hello进程的时候,会打印出系统的环境变量
通过在execve进程里调用execve函数可以调用子进程hello,并自定义环境变量,execve进程最后那个打印操作并不会再执行

0 0