I have a signal handler in C++ program:

void term(int signum)
    cout << "in term" << endl;
    # Do Stuff

int main(int argc, char *argv[])
    # Do Stuff
    signal(SIGINT, term);
    # Do Stuff

The program works fine. goes in the function term when I press Ctrl+C and exits.

However, when I try to replicate the behavior using a script, it does not work.

Simplified version of the script I am running:

! /bin/bash
sudo ./program &

sleep 2
sudo kill -INT $rpid
# sudo kill -TERM $rpid
# sudo kill $rpid

echo "killed"
wait $rpid

The program is does not even go in the term function until I press Ctrl+C. It is stuck on wait indefinitely.

  • The title asks about the difference between Ctrl-C and kill -INT? The body is about the difference between C and a shell script. OR did I miss-read it (In which case it is confusing). Jan 10 '20 at 17:08
  • Even in those small snippets you're doing a lot of dubious things like a) use iostreams in signal handlers b) calling exit(3) from a signal handler c) using signal() (which nobody actually knows how it works) instead of sigaction(2) d) pointlessly using sudo, etc. Please submit a reproducible example.
    – mosvy
    Jan 10 '20 at 17:09
  • First you can not (normally) send signals to a process running as root, when not root. And second you can not ctrl-C a process that is running as a background job. Jan 10 '20 at 17:12
  • @Mosvy OK so I miss-read it. The problem with the question is that it took two reading. There is a bit where is tells the reader that it is about to show a shell script alternative to the C program. But then we realise that it is an alternative to the manual operation. Well it is ambiguous, so half of readers will go one way, and half the other, on first reading. Jan 10 '20 at 17:15
  • you cannot use iostreams or stdio functions inside signal handlers. Replace it with write(1, "in term\n", 8); Anyways, try submitting a complete reproducible example.
    – mosvy
    Jan 10 '20 at 17:15
% sudo sh -c 'exec echo My process ID is $$.' & echo "Xyr process ID is $\!." ; wait
[1] 59130
Xyr process ID is 59130.
My process ID is 59131.
[1]  + done       sudo sh -c 'exec echo My process ID is $$.'

Welcome to the world of Pluggable Authentication Modules! Programs like login, su, and sudo do not overlay themselves with the target program any more.

You are sending your signals to the wrong process.

Further reading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.