简体   繁体   中英

signal handler ending the process after its execution

I'm coding a program and I settled up a signal handler for SIGINT :

volatile int exit_program = 0; //Global variable

void exit_client() {
    write(1, "Disconnecting...\n", strlen("Disconnecting...\n"));
    exit_program = 1;
}

Then in main I told the process to react with exit_client() when a SIGINT is received.

int main() {
    signal(SIGINT, exit_client);
    //...
}

Later on in the main process I have the following code:

while (!exit_program) {

    //...

    socket_rcv(server_socket);
}

close(server_socket);
write(1, "Disconnected\n", strlen("Disconnected\n"));
    

I use socket_rcv() to receive data from the server socket and also to send a SIGINT to the process if the read() return value is 0 (when the server disconnects). I do this executing: raise(SIGINT) :

socket_data socket_rcv(int socket) {
        
    //...

    do {
        bytes_read = read(socket, sequence + (115 - total_bytes), total_bytes+10);

        if (bytes_read == -1) write(1, "Read error\n", strlen("Read error\n"));
        if (bytes_read == 0) raise(SIGINT);
        total_bytes -= bytes_read;

    } while (total_bytes > 0);

    //...
}

But, when executing both server and client and disconnecting the server first, to see how the client reacts (should print Disconnecting... and then Disconnected as well as the server socket is closed), I only get the print in the signal handler to confirm the signal handler executes but then the program terminates and it doesn't continue it's execution in order to close the socket and execute the last write(1, "Disconnected\n", strlen("Disconnected\n")); .

Why does it terminate and how can I fix this?

Also, might be irrelevant but socket_rcv() function is declared in another .c file, including its .h module where the main process is.

I agree with the commenters, why use a signal handler when you can set exit_program directly?

Anyway, your problem seems to be lying somewhere else (maybe read ?) or you're not giving us the full picture because this piece of code works:

#include <signal.h>
#include <string.h>
#include <unistd.h>

volatile int exit_program = 0;

void exit_handler(int sig) {
    write(1, "exit_handler\n", strlen("exit_handler\n"));
    exit_program = 1;
}

int main() {
    int i = 0;

    signal(SIGINT, exit_handler);

    while (!exit_program) {
        write(1, "loop\n", strlen("loop\n"));

        if (i == 1) {
            raise(SIGINT);
        }

        ++i;
    }

    write(1, "done\n", strlen("done\n"));

    return 0;
}

Prints

loop
loop
exit_handler
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM