Marco
Marco

Reputation: 625

User defined signal 1

I'm developing a client-server program and when I'm trying to send a signal to another process, it just display this sentence "User defined signal 1". As you can see in the code, I am using the SIGUSR1.

Client:

void Exit(req req)
{
    kill(req.server_pid, SIGUSR1);
    fprintf(stdout,"\n[CLIENT] Closing the client...\n");
    sleep(2);
    unlink(FIFO_CLIENT);
    exit(0);
}

Server:

void ClientLeft (int sig)
{
    fprintf(stdout,"\n[CLIENT] Just left the game!");
}

int main()
{
    signal(SIGUSR1, ClientLeft);
}

I don't understand why the client doesn't run the rest of the lines, and even the server doesn't show the printf.

Upvotes: 1

Views: 25325

Answers (1)

You should read carefully signal(7) and signal-safety(7) ...

You'll understand why your code is against the rules (in principle you should never use printf or fprintf inside a signal handler, see also explanations about calling Qt functions from Unix signals).

Then, you should remember that stdio(3) is buffered. So add a \n at end of your printf format string. Or call fflush(3) or setvbuf(3).

The good habit to have is to always end printf format strings with \n and if you don't do that, call fflush(NULL) at appropriate places.

Also, use strace(1) on both client and server code to check that SIGUSR1 signal was indeed sent and handled.

Your main function (as you show it on the server side) is too short. The process running your main is very probably exiting before having any chance to get any signal. On my computer your "server program" runs in less than a millisecond.

At last, using signals is very probably a bad way to communicate between server and clients. Consider using pipe(7), fifo(7), unix(7), socket(7), eventfd(2), poll(2), read(2), write(2) and other syscalls(2). Read also Advanced Linux Programming

If you use a recent GCC compiler, be sure to enable all warnings and debug info, so compile first with gcc -Wall -Wextra -g.

Upvotes: 9

Related Questions