如何从该 C 程序执行 C 程序的 shell 中更改环境变量? [英] How to change environment variable in shell executing a C program from that C program?

查看:20
本文介绍了如何从该 C 程序执行 C 程序的 shell 中更改环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 C 程序中更改 PATH 变量的值,然后在我运行此程序的 shell 中查看更改后的值.

I want to change the value of PATH variable inside the C program and then see the changed value in the shell using which I run this program.

做这样的事情,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main () {

    char *path = getenv ("PATH");
    printf ("%s\n\n", path);
    setenv ("PATH", strcat (path, ":~/myNewPath/"), 1);
    printf ("%s\n\n", path);

    int pid = fork ();
    if (pid == -1)
        abort ();
    if (pid == 0) {

    } else {
        // use execlp? how? source? any hints?
    }

    return 0;
}

如果我在 exec* 系统调用中使用 source 命令.在 shell 中向后更新这个 PATH 变量的语法是什么?

If I use source command in the exec* system call. What will be the syntax to update this PATH variable in the shell backwards?

推荐答案

这是不可能的.子进程无法更改其父进程的环境变量.

This is impossible. There is no way for a subprocess to change its parent's environment variables.

要了解为什么这是不可能的,请查看<的签名代码>执行

To understand why it is impossible, look at the signature of execve

int execve(const char *program, char *const *argv, char *const *envp);

在Unix系统上与maintrue签名配对

which is paired with the true signature of main on Unix systems

int main(int argc, char **argv, char **envp);

也许您开始明白,就内核而言,环境变量是第二组命令行参数.它们看起来可以通过getenvsetenv等独立访问,并且看起来从父级继承到子级,是 C 库维护的错觉.

and perhaps you begin to understand that as far as the kernel is concerned, the environment variables are a second set of command line arguments. That they appear to be independently accessible via getenv and setenv etc, and appear to inherit from parent to child, is an illusion maintained by the C library.

有关其工作原理的更多详细信息,请研究 x86-64 ELF ABI 规范,第 3.4.1 节初始堆栈和寄存器状态" 特别注意图 3.9,它显示了由 execve 复制到新创建的堆栈上的数据的布局.(链接的文档特定于一种 CPU 架构,但其工作方式在现代 Unix 中通常是一致的;细节当然会因 CPU 和 CPU 以及操作系统而异.)

For more detail on how this works, study the x86-64 ELF ABI specification, section 3.4.1 "Initial Stack and Register State" paying particular attention to figure 3.9 which shows the layout of the data copied by execve onto the newly created stack. (The document linked is specific to one CPU architecture, but the way this works is generally consistent across modern Unixes; fine details will of course vary from CPU to CPU and OS to OS.)

这篇关于如何从该 C 程序执行 C 程序的 shell 中更改环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆