C Programming Examples Tutorial Index

C Function Programs

In this C programming example, a simple C program is displayed that shuts down a PC by calling internal OS features. This type of functionality can be helpful where sometimes you have to shut down or restart the PC due to some requirement, like after updating the system driver.



What Is System Shutdown

A shutdown is a mechanism for safely shutting down the system. In this process, all logged-in users are first notified that the system will be turned off, and in the last five minutes, new logins are prevented.

C Program to Shuts down a Windows PC

A simple C program to shuts down a Windows PC by calling internal Windows features:

Example C Program:
#include <stdio.h>
#include <stdlib.h>

void main() {
  char ch;

  printf("Are you sure you want to turn off your computer now? (y/n)\n");
  scanf("%c", &ch);

  if (tolower(ch) == 'y')
    /* Call Windows OS commands using the system() function. */
    system("C:\\WINDOWS\\System32\\shutdown /s");
}

Program Output:

Are you sure you want to turn off your computer now? (y/n)
Y

The system() function is a part of the <stdlib.h> header file. You must include it in the program to perform this operation.

Command for Restart or Logoff Windows Pc

To perform similar operations such as PC restart or User logoff, replace the last character in the system command path, such as:

system("C:\\WINDOWS\\System32\\shutdown /r"); /* restart */
system("C:\\WINDOWS\\System32\\shutdown /l"); /* logoff */

In earlier versions of Windows, such as Windows XP, a dash is used as a prefix instead of a forward slash.

Example C Program:
system("C:\\WINDOWS\\System32\\shutdown -s");

Setting Timer to Delay Execution in Windows PC

In Windows, the shutdown command gets executed immediately. Still, if you want it to execute after some time, you can append a parameter to the system function and instruct it to delay.

system("C:\\WINDOWS\\System32\\shutdown /s /t 15"); /* shutdown after 15 seconds */

C Program to Shuts down a Linux PC

To do the same thing in Linux, you have to change the command parameter; the rest of the code will remain the same.

Example C Program:
#include <stdio.h>
#include <stdlib.h>

void main() {
  char ch;

  printf("Are you sure you want to turn off your computer now? (y/n)\n");
  scanf("%c", &ch);

  if (tolower(ch) == 'y')
    /* Call Linux OS commands using the system() function. */
    system("shutdown -P now");
}

Setting Timer to Delay Execution in Linux PC

Linux also executes the commands immediately because the "now" parameter is defined at the end of the command. Instead of "now", you can specify the number of seconds as long as you want to delay execution.

system("shutdown -P 10"); /* shutdown after 15 seconds */

The shutdown command also has some options; you can execute "man shutdown" in the command prompt to know more.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram