I have written a program that invokes a system command from inside:
#include <stdlib.h>
int main(void)
{
while(1)
{
system("ls 2>&1 1>/dev/null"); // comment this line out to enable ctrl+break
}
return 0;
}
However, when it is running, CTRL+C and CTRL+BREAK no longer work and appear to be ignored.
I am trying to write a program that performs some operations in the background involving the shell, but I also want to be able to break out of the program when the user wants to break.
Is there a way to make it work the way I want? Should I change the architecture to perform some kind of fork / exec?
From the POSIX specification for
system():So, in order to respond properly to signals, you need to examine the return value of
system().And the docs of
waitpid()refer to the docs forwait(), which instruct you to use the following macros to find out why a process exited:Here is an example of how you would use this information, without having to fork a separate process. Note that you won’t actually receive the signal in the parent process, but you can determine the signal sent to the child process:
And if you run it, you get: