angry somoan angry somoan - 1 month ago 7
C Question

simple delayed shutdown app in ANSI C, also switch acting weird

At the beginning i wanted to point out the fact, that I'm a complete beginner with C and programming. I'm trying to make some simple console app to schedule delayed shutdown of my PC.
Here's my code:

int main()
{
int minutes, seconds;
char command[50];
char sa;

printf("(s)hutdown or (a)bort?. 0 to exit.\n");
scanf("%c", &sa);
switch (sa)
{
case 's':
printf("How many minutes till shutdown\n");
scanf("%d\n", &minutes);
seconds = minutes * 60;
sprintf(command, "shutdown /s /f /t %d\n", seconds);
system(command);
system("exit");

case 'a':
sprintf(command, "shutdown /a");
system(command);
system("exit");

default:
printf("Bad choice.");
system("exit");
}

return 0;
}


My problems are:

1. When I choose 's', and after writing down appropriate amount of minutes and pressing enter
system('exit')
should close the console, but that doesn't work. I have to write down anything to get it closed. And even after that case 'a' is being executed anyway, cancelling any delayed shutdown.

2. After choosing 's' or 'a' the default case is executed as well. So the output I get always ends with "Bad choice."

Could somebody help me out with my (probably stupid) problem? Thank you very much for any help!

Answer

The system function starts a new shell, so

system("exit");

will just exit from that new shell, returning execution control back to your program.

To kill the parent shell you can probably send it a SIGHUP signal.

Comments