Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use SIGINT to break out of the wait for accept() or read()?

Tags:

c

sockets

sigint

I'm currently trying to break out of the wait for accept() and/or write() by using signals, in this case SIGINT. My the program doesn't leave either as expected.

void sigHandler(int signal ){

    printf(" Exit\n");

    //x is global
    x = 1;

    return;

}

My snipped from main I'm getting hung up on is mainly:

 clientfd = accept( sockfd, (struct sockaddr *) &client_addr, (unsigned int *) &client_addr_len );

When I hit this and use my signal and return, I'm still stuck on this line of code, waiting for a user to connect to my socket. The x in the handler is to for the outer loop this piece of code is in.

Is there a better way to do what I'm trying to do? Also, let me know if this isn't enough information.

Thank you.

Edit:

Here is the check for the signal, which is back at the top of main. I think this is what you were asking for:

if ( signal( SIGINT, signalhandler ) == SIG_ERR ){
    return( 1 );
}
like image 737
nzondlo Avatar asked Jan 15 '23 00:01

nzondlo


1 Answers

If you establish the signal handler using signal, then the accept is automatically restarting. Using signal is similar to using sigaction with sa_flags set to include SA_RESTART. Instead of signal, use sigaction and make sure that the sa_flags field of the struct sigaction does not have the SA_RESTART bit set.

In other words, instead of: signal( SIGINT, signalhandler ), use:

struct sigaction a;
a.sa_handler = signalhandler;
a.sa_flags = 0;
sigemptyset( &a.sa_mask );
sigaction( SIGINT, &a, NULL );
like image 102
William Pursell Avatar answered Jan 31 '23 01:01

William Pursell