Simple code:
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
using namespaces td;
bool unblock = false;
long int ile = 0;
void ouch(int sig) {
cout << "signal " << sig << endl;
unblock = true;
}
int main(){
struct sigaction act;
act.sa_handler = ouch;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGINT, &act, 0);
do {
cout << "." << endl;
} while(!unblock);
cout << "EXIT" << endl;
}
Now i compile the code and i get the “a.out”.
When i run the a.out like this:
[przemek@localhost test]$ ./a,out
it runs just as expected and when i press CTRL+C the program exits just as needed
But when i run the program like this (which is needed in my project):
[przemek@localhost test]$ ./a.out&
The os passes the control to the shell and i am unable to break the loop by CTRL+C
I need to run this code in bash script and i need to run it in background. Is it possible to somehow catch the signals in such situation?
When you press
ctrl-cyou send signal 2 (SIGINT) to current process (the process that runs in foreground on the terminal). You can send the signal to process that runs in background (was started with &) usingkill:When you say
%%you mean the last background process. Of course you can specify another one. You need to know its PID (see ps(1)) or JobID (bash(1)/jobs).I want to note also that you can use %-notation only inside shells with jobs management (e.g. in
bash). When you are not in such a shell you can use only PIDs.The PID of the last started process is in
$!. That may be useful in some scripts.