简体   繁体   中英

Cross-platform way to shutdown the computer

I'd like to implement a cross-plaftorm function to shut down the computer without using any system specific API, but the "stdlib.h" std::system function. I have hardly found any reliable resource on the web about it.

On Windows systems the following does the job:

#if defined(_WIN32) || defined(__WIN32) || defined(__WIN32__)
std::system("shutdown -s -t 0");
#endif

What should be the command on other operating systems (like Linux, Mac OSX, etc..)?

There is no cross platform shutdown command.

You need to take a look at the shutdown command in the OS you want to have it and then check what OS the client is running and depending on that you can select the right command or code to shut down the specific system.

On your *nix systems the following should work.

#include <cstdlib>

int main() 
{
  system("shutdown -P now");
  return 0;
}

However, the above code assumes that you are logged in as the root and if you are not you will get an error while not being logged in as root.

There is no "cross platform" way of doing this except to use a switch statement or if - else statement series for correct syntax of the specified OS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM