My C++ program does some work, and then waits for a signal to kill it. I'd like to just exit, but exiting sends SIGCHLD to parent process, and I need to control the timing of that.

So currently I do following:

int main() {
    run(); // do stuff, then free() and close() everything possible.
    for (;;) pause();  // wait for signal to kill us
    return 0;

So after run() is completed, the program just sits there and then dies.

Is there some nice linux-y way to say "this program doesn't need anything now, deallocate stack and everything else", or I am already at the "barest process possible" stage?

  • 1
    I can not see why it is the childs responsibility. Why can't the parent handle a signal coming in? – ctrl-alt-delor Nov 23 '18 at 11:40
  • Parent does handle SIGCHLD and does some cleanup in the handler. I need to control when that happens. – Andrew Morozko Nov 23 '18 at 11:46
  • Yes but why do you have to control that? You may have other problems, that need fixing. – ctrl-alt-delor Nov 23 '18 at 11:49
  • @ctrl-alt-delor yeah, I’m just wondering how cleanly I can do this without modifying the server(parent process in this case). I don’t really want to get into server’s code, it’s complicated... – Andrew Morozko Nov 23 '18 at 11:58
  • That is a good thing to consider, but usually things go better if we try to fix it up stream. If we fix it down stream, then every cup of water need cleaning, this will cost more than fixing it up-stream. I am about to add another idea to my answer. – ctrl-alt-delor Nov 23 '18 at 12:11

Suppose you have to do what you say (which I doubt), and suppose your program is big, so uses a lot of memory.

idea 1

You could exec another smaller program, to do the waiting.

However the most efficient way is to exit, this well free almost everything, except your entry in the process table, and your exit value. The process will then become a zombie, until the parent handles the SIGCHLD (or the parent dies, in which case `init becomes parent, and handles SIGCHLD very quickly).

Idea 2

Write a wrapper. This way the child does not need modifying, you are no-longer warping the child code, to compensate for bad parenting.

The wrapper can contain nothing more than, run child, wait, exit. e.g.

int main() {
    fork and exec child
    wait for child
    wait for signal from parent
    return child exit code

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.