4

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 );
}
nzondlo
  • 4,166
  • 4
  • 18
  • 20
  • 1
    Show the code of relation between your signal handler and socket. – masoud Mar 08 '13 at 20:19
  • I know the prototype for signal() says the handler can only have one argument that is the 'signal' itself. I'm not sure how to change the 'sockfd' socket in the handler if I can't pass it in. – nzondlo Mar 08 '13 at 20:29

1 Answers1

10

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 );
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 1
    And don't forget to check your function error returns for EINTR. – Zan Lynx Mar 08 '13 at 22:13
  • In my case, I was using sigaction, but hadn't realized that the existing action I was getting has SA_RESTART already set on it. – Rob_vH Mar 04 '15 at 21:31