me_L_coding
me_L_coding

Reputation: 354

Unix programming - signal handler

I've run into some problems while trying to write a smallshell in c.

The problem is the following: Assume I have written some code for a signal-handler that, in this case, is modified to catch SIGCHLD signals, how could I notify my program that a signal has been caught?
The problem is easy if I were to use a global variable, but that's not really the way I want to go about it. So any suggestions/hints would be much appreciated!

This is how I solve it right now.

volatile sig_atomic_t exit_status; /* <--global variabel */

void sigchld_handler(int signal) {
    switch (signal) {
    case SIGCHLD:
        exit_status = 1; /* SIGCHLD was caught, notify program.. */
        break;
    default:
        fprintf(stderr, "Some signal catched\n"); /* not a signal of intrest */
        break;
    }
}

//Thanks

Upvotes: 1

Views: 554

Answers (3)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136208

A standard solution is to use the unix self-pipe trick. The benefit is that the read end of the pipe can be used with select() or epoll() thus integrating nicely with event loops without having to periodically poll the value of an atomic variable.

Upvotes: 3

Teemu Ikonen
Teemu Ikonen

Reputation: 11929

To be honest for me this looks like perfect case for global variable. But if you don't want to do that there are lots of alternatives: http://beej.us/guide/bgipc/output/html/multipage/index.html Pick one from the list that suits best on your architecture.

Upvotes: 1

sarnold
sarnold

Reputation: 104020

signal(7) contains a list of functions that are safe to execute in signal handlers; fprintf(3) isn't one of them. What happens if a child dies while your shell is printing the prompt or status messages? Corrupted data-structures is the usual result. (This is fine for toys -- but I wouldn't want this in a shell.)

Setting global variables is quite typical for signal handlers. It's an easy way to signal the process's main event loop or main processing loop that something else needs to be done.

Upvotes: 1

Related Questions