-1

I want to shutdown PC with C without using system() functiom

#include <stdio.h>
#include <Windows.h> 
int main(){
    system("shutdown -s -t1");
}

I'd like to find better way.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Abdallah
  • 15
  • 8
  • Something like this. Just find the equivalent in c https://stackoverflow.com/questions/102567/how-to-shut-down-the-computer-from-c-sharp – drum Nov 11 '22 at 17:27
  • 2
    @drum: Bad dupe. He doesn't want to start shutdown.exe. – Joshua Nov 11 '22 at 17:54
  • @Joshua why was it a bad dupe? One of the answers is to use the API ExitWindowsEx – drum Nov 12 '22 at 15:34

2 Answers2

3

You can shut down the Windows operating system using the function ExitWindowsEx with the EWX_SHUTDOWN or EWX_POWEROFF flag.

However, as stated in the documentation, the calling process will require the SE_SHUTDOWN_NAME privilege. See the documentation on how to allow the process to obtain that privilege.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • There is way to add timer? – Abdallah Nov 11 '22 at 17:39
  • @Abdallah: A timer for what exactly? Do you want to initiate a shutdown when the timer reaches zero? – Andreas Wenzel Nov 11 '22 at 17:41
  • yes I want user to set time and when time be 0 computer shutdown – Abdallah Nov 11 '22 at 17:45
  • @Abdallah: See [this documentation](https://learn.microsoft.com/en-us/windows/win32/winmsg/about-timers) for an overview of timers using the Windows API. The function `SetTimer` will probably be sufficient for what you want. – Andreas Wenzel Nov 11 '22 at 17:51
  • @AndreasWenzel: There should be an API equivalent of `-t1`. I don't know it or I'd answer. – Joshua Nov 11 '22 at 17:51
  • 2
    @Joshua: The function [`InitiateSystemShutdown`](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-initiatesystemshutdowna) has a `dwTimeout` argument, which may be the equivalent of the `-t1` command-line argument to `shutdown`. I am not sure. – Andreas Wenzel Nov 11 '22 at 18:01
  • 1
    Another option is to use `Sleep()` in the program. – the busybee Nov 11 '22 at 19:37
2

This is managed by the operating system, so you'll have to figure out how to do it on your OS.

It looks like you're using Windows, so you could try the Windows API's System Shutdown Functions.

Josh Kelley
  • 56,064
  • 19
  • 146
  • 246