开发者

Run command in linux terminal using java program?

I want to run unset DISPLAY as a command in the linux terminal, using a Java pro开发者_运维知识库gram.

I tried using Runtime.getRuntime().exec("unset DISPLAY");, but it doesn't work.

What could I do here?


This won't work, and here's why. Environment variables are inherited from the parent process. A child can't control a parent's environment. Here's what's happening in your setup:

 bash   ->   java   ->   unset
   |           |           |
 parent      child     grand-child
   |           |           |
unaffected unaffected   affected

So in actuality your command IS working, however it's not having the effect you want it to. Sadly java won't be able to change the parent's environment.

Your java program can modify environment variables of its own, and any children spawned by java will inherit those variables. So you could potentially have java launch a bash shell for you, and then use that bash shell interactively, but that seems like a lot of overhead.

See this post for how to set java's environment variables:
How do I set environment variables from Java?

If you're willing to sidestep the whole java problem, what most people do in this situation is source a special file. For example, create a file called "no-x.sh" that looks like this:

# Unset the display variable
unset DISPLAY

And then from your current (interactive) shell, source the file like this:

$> source no-x.sh

and now your main bash shell has had its environment changed. Note that this is a HACK (or for all of you bash zealots out there -- a feature) and you should never expect to duplicate this functionality with anything else (like java).


You need to run it using bash executable like this:

 Runtime.getRuntime().exec("/bin/bash -c \"unset DISPLAY\"");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜