Introduction
In this lab, we will learn how to write a program in C to shut down a Windows or Linux computer using the system() function. We will provide step-by-step instructions on how to create a program that will allow a user to shut down their computer system with ease.
Setting up the Environment
To write this program, we will be using the code editor in the Ubuntu virtual machine. Open up your terminal and type the following command to create a new directory named Windows-Linux-Shutdown-Program:
mkdir Windows-Linux-Shutdown-Program
Then, navigate to the directory by typing:
cd Windows-Linux-Shutdown-Program
Next, create a new C file named main.c by typing:
touch main.c
And open it in the code editor by typing:
nano main.c
Creating the Program
Now that we have our environment set up, we can begin creating our program. Copy and paste the following code into your main.c file:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Do you want to shutdown your computer (y/n)? ");
scanf("%c", &ch);
if(ch == 'y' || ch == 'Y')
{
#ifdef _WIN32
system("shutdown /s /t 0");
#elif defined __linux__
system("shutdown now -P");
#endif
}
return 0;
}
This program will prompt the user to enter 'y' or 'n' to indicate whether or not they want to shut down their computer. If they enter 'y', the program will then use the appropriate system() function to shut down the computer.
Compiling the Program
To compile the program, we will use the following command:
gcc main.c -o shutdown
Running the Program
To run the program, type the following command:
./shutdown
The program will prompt the user to enter 'y' or 'n' to indicate whether or not they want to shut down their computer. If they enter 'y', the program will then use the appropriate system() function to shut down the computer.
Testing the Program
Test the program by running it and entering 'y' to shut down your computer. If everything is working correctly, the program should shut down your computer immediately.
Viewing the Full Code
Here is the full code of the main.c file:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Do you want to shutdown your computer (y/n)? ");
scanf("%c", &ch);
if(ch == 'y' || ch == 'Y')
{
#ifdef _WIN32
system("shutdown /s /t 0");
#elif defined __linux__
system("shutdown now -P");
#endif
}
return 0;
}
Summary
In this lab, we learned how to write a program in C to shut down a Windows or Linux computer using the system() function. We provided step-by-step instructions on how to create a program that will allow a user to shut down their computer system with ease. By following these steps, you should now be able to create your own Windows or Linux shutdown program using C.



