Writing a small C program to shutdown windows in entered time

Go To StackoverFlow.com

3

I want to write a program to shut down windows in N seconds. The easiest method I know to shutdown windows is to call system() with

shutdown -s -t XXXX

where XXXX is the given time. However system() only accepts string as a parameter. How can I call system("shutdown -s -t 7200") where 7200 is inputed by the user?

2012-04-03 20:10
by muntasir2000
system isn't really the best way to do this. Simply call <code>InitiateSystemShutdown</code> - David Heffernan 2012-04-03 20:14
so where are you stuck? Getting the user input? Appending it as a string to the system call? Somewhere else - AShelly 2012-04-03 20:16


1

I'd use InitiateSystemShutdown instead. You could use ExitWindows or ExitWindowsEx, but neither of those directly supports the delay being asked about in the original question, so you'd have to add code to do that delaying (e.g., using SetTimer). That's certainly possible, but incurs extra work without accomplishing anything extra in return.

If you insist on using system, you can use sprintf (or something similar) to create the string you pass to system:

char buffer[256];

sprintf(buffer, "shutdown -s -t %d", seconds);
system(buffer);
2012-04-03 20:14
by Jerry Coffin
I think to call ExitWindows the OP would need elevated rights, otherwise +1 - user7116 2012-04-03 20:21
@sixlettervariables: Nearly anything that attempts to shutdown the computer needs the SESHUTDOWNNAME privilege, whether done via InitiateSystemShutdown, ExitWindows(Ex), or shutdown on the command line. Although it was edited in, I would recommend against ExitWindows(Ex) under the circumstances. To use them after a delay, you'd have to handle the delay part yourself -- extra work for no gain - Jerry Coffin 2012-04-03 20:25
I believe <code>shutdown</code> does that internally is all I'm pointing out - user7116 2012-04-03 20:28
It's pretty unusual for a user not to have sufficient rights to shut the machine down - David Heffernan 2012-04-03 20:31
@DavidHeffernan: What (I think) he's pointing out is that you have to enable the privilege before using it. It's true, and I suppose it might (just possibly) be a line or two longer than the code to do sprintf safely, but certainly not much more than that - Jerry Coffin 2012-04-03 20:35


1

Take a look at scanf() and sprintf(), e.g.:

#define MAX_LENGTH 50
/* ... */
int shutdownTime;
char shutdownCall[MAX_LENGTH];

scanf("%d", &shutdownTime);
if (shutdownTime < 0) 
    return NEGATIVE_TIME_ERROR;
sprintf(shutdownCall, "shutdown -s -t %d", shutdownTime);
system(shutdownCall);
2012-04-03 20:17
by Alex Reynolds
Ads