Reputation: 2061
I wrote console program that detects SIGINT, so when user press Ctrl+C program performs some actions and terminates.
But when I redirect this program with pipe to any other, for example:
./my_program | tee xxx
SIGINT never comes to my handler. Despite this program terminates.
Handing SIGTERM gives no effects. SIGTERM does not come after Ctrl+C too.
How can I detect that program is aborted by Ctrl+c in all situations?
My test case with SIGINT and SIGPIPE:
#include <csignal>
#include <cstdio>
bool break_request=false;
bool term_request=false;
extern "C" void break_handler(int)
{
break_request=true;
printf("Ctrl+C detected\n");
}
extern "C" void term_handler(int)
{
term_request=true;
printf("pipe detected\n");
}
int main()
{
signal(SIGINT,break_handler);
signal(SIGPIPE,term_handler);
while(true)
{
if(break_request)
{
printf("break request handled\n");
break;
}
if(term_request)
{
printf("pipe request handled\n");
break;
}
}
printf("terminating\n");
}
Upvotes: 2
Views: 1128
Reputation: 3684
Your printf
output is going down the pipe. Use fprintf(stderr, "...")
instead.
Upvotes: 3
Reputation: 213758
If your program is used in a pipe, it will get SIGPIPE
if it writes when there's no reader on the other side.
Just install a SIGPIPE
handler.
Upvotes: 0