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...
", strlen("Disconnecting...
"));
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
", strlen("Disconnected
"));
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
", strlen("Read error
"));
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
", strlen("Disconnected
"));
.
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.
question from:
https://stackoverflow.com/questions/65647693/signal-handler-ending-the-process-after-its-execution 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…