I would like to write a program in C that can shutdown a computer. In order for me to do this, I must execute the command "shutdown -h now". This is to be done in the terminal or command prompt. How can I tell the program I would like it to execute the command in the command line?
3 Answers
There is a system-function, which basically does the c equivalent of the assembly systemcall: It is located in
system("cls");
will clear the command screen for example.

- 2,419
- 2
- 18
- 30
To run a command in simple covenient way from C, use system
:
system( "date");
That will execute the command under POSIX OSes, with the shell using your standard environment, so PATH is respected. Unfortunately, "shutdown -h now" requires privileges, so you may need to use sudo and enter a password.

- 1,396
- 8
- 10
You've got a bunch of functions which can do what you want:
- system("shutdown -h now");
- the exec* family : execlp("/sbin/shutdown", "shutdown", "-h", "now");
- popen("shutdown -h now");
They all have advantages and drawbacks.
For example popen will return a FILE* which contains the output of the executed command.
Exec* will simply replace the memory area with your program by the one of the executed binary, this way if you want to continue the execution of your program you will have to use fork(2).
System is simply a helper function using fork and exec*.

- 632
- 7
- 20