Is there a way to change the environment variables

2019-01-01 03:40发布

On Unix, is there any way that one process can change another's environment variables (assuming they're all being run by the same user)? A general solution would be best, but if not, what about the specific case where one is a child of the other?

Edit: How about via gdb?

10条回答
看风景的人
2楼-- · 2019-01-01 04:08

Quoting Jerry Peek:

You can't teach an old dog new tricks.

The only thing you can do is to change the environment variable of the child process before starting it: it gets the copy of the parent environment, sorry.

See http://www.unix.com.ua/orelly/unix/upt/ch06_02.htm for details.

Just a comment on the answer about using /proc. Under linux /proc is supported but, it does not work, you cannot change the /proc/${pid}/environ file, even if you are root: it is absolutely read-only.

查看更多
牵手、夕阳
3楼-- · 2019-01-01 04:10

Via gdb:

(gdb) attach process_id

(gdb) call putenv ("env_var_name=env_var_value")

(gdb) detach

This is quite a nasty hack and should only be done in the context of a debugging scenario, of course.

查看更多
人气声优
4楼-- · 2019-01-01 04:13

Substantially, no. If you had sufficient privileges (root, or thereabouts) and poked around /dev/kmem (kernel memory), and you made changes to the process's environment, and if the process actually re-referenced the environment variable afterwards (that is, the process had not already taken a copy of the env var and was not using just that copy), then maybe, if you were lucky and clever, and the wind was blowing in the right direction, and the phase of the moon was correct, perhaps, you might achieve something.

查看更多
笑指拈花
5楼-- · 2019-01-01 04:16

You probably can do it technically (see other answers), but it might not help you.

Most programs will expect that env vars cannot be changed from the outside after startup, hence most will probably just read the vars they are interested in at startup and initialize based on that. So changing them afterwards will not make a difference, since the program will never re-read them.

If you posted this as a concrete problem, you should probably take a different approach. If it was just out of curiosity: Nice question :-).

查看更多
何处买醉
6楼-- · 2019-01-01 04:20

Not as far as I know. Really you're trying to communicate from one process to another which calls for one of the IPC methods (shared memory, semaphores, sockets, etc.). Having received data by one of these methods you could then set environment variables or perform other actions more directly.

查看更多
倾城一夜雪
7楼-- · 2019-01-01 04:22

UNIX is full of Inter-process communication. Check if your target instance has some. Dbus is becoming a standard in "desktop" IPC.

I change environment variables inside of Awesome window manager using awesome-client with is a Dbus "sender" of lua code.

查看更多
登录 后发表回答