This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
hi ,everybody , i wanner write some codes in order to control pc , such as shutdown pc ,reboot pc . i don't like the way follow codes:
Runtime run = Runtime.getRuntime();
run.exec("sudo shutdown -h now")
You could write a JNI class that invokes the OS-level functions directly.
Although rebooting an OS from inside any application is a questionable practice. I'd generally put the application in a shell script and have it set an exit code that would then determine what, if any reboot-style action would be done by the next step in the shell script. That way I'd have an app that shutdown clean, and wouldn't have to worry about it maybe going crazy and rebooting unexpectedly due to a bug.
An IDE is no substitute for an Intelligent Developer.
Joined: Apr 21, 2009
i think that isn't safety , it can achieve that with shell only.
The difference is that the shell script is a text file. To monitor its behavior, you can simply list it. System-controlling shell scripts tend to be fairly simple and straightforward.
Applications, on the other hand, are binary "black boxes", and if the application's primary purpose is something other than simple system control, there's always a chance that there may be unforseen logic paths that can cause the system to shut down unexpectedly.
This isn't to say that shell scripts are absolutely safer, but they are more transparent.
The real reason why I'd prefer the shutdown to be done outside the app, however, is that that way the app will have been terminated (hopefully cleanly) before the shutdown process begins. So you won't have the danger of OS yanking resources out from under you while the app still has threads executing, buffers unflushed, network connections open, etc.