You are here

C program to shut down or turn off computer

C program to shut down your computer, i.e., to turn off a computer system. System function of "stdlib.h" is used to run an executable file "shutdown.exe" which is present in C:\WINDOWS\system32 folder in Windows 7 & XP. See Windows XP and Linux programs at the bottom of this page.

C program for Windows 7

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   system("C:\\WINDOWS\\System32\\shutdown /s");
 
   return 0;
}

You can use various options while executing "shutdown.exe," for example, you can use /t option to specify the number of seconds after which shutdown occurs.

Syntax: "shutdown /s /t x"; where x is the number of seconds after which shutdown will occur.

By default, shutdown occurs after 30 seconds. To shut down immediately you can write "shutdown /s /t 0". If you wish to restart your computer, then you can use "shutdown /r."

C program for Windows XP

It will ask if you want to shutdown your computer, if you press 'y' then your computer will shutdown in 30 seconds.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char ch;

   printf("Do you want to shutdown your computer now (y/n)\n");
   scanf("%c", &ch);

   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown -s");

   return 0;
}

To shutdown immediately use "C:\\WINDOWS\\System32\\shutdown -s -t 0". To restart use "-r" instead of "-s".

If you are using Turbo C Compiler then execute your program from command prompt or by opening the executable file from the folder. Press F9 to build your executable file from source program. When you run program from within the compiler by pressing Ctrl+F9 it may not work.

C program for Ubuntu Linux

#include <stdio.h>

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

You need to be logged in as root user for this program to execute otherwise you will get the message shutdown: Need to be root, now specifies that you want to shut down immediately. '-P' option specifies you want to power off your machine. You can specify minutes as:
shutdown -P "number of minutes."

For more options or help type "man shutdown" in a terminal.

Share this