开发者

send( ) problem

开发者 https://www.devze.com 2023-02-24 09:16 出处:网络
When I test my program using a web browser I can write to the socket/FD just fine so i decided to loop it and cut the connection mid-connection and I noticed a problem. send() is开发者_高级运维 capabl

When I test my program using a web browser I can write to the socket/FD just fine so i decided to loop it and cut the connection mid-connection and I noticed a problem. send() is开发者_高级运维 capable of closing down the entire program when the socket is unavailable. I thought the problem was that the program caught itself in a catch-22 and closed itself. So I set the socket to not block. No change. Any ideas of why this is happening?

else if ( b->temp_socket_list[read].revents & POLLOUT ) {  
    printf ( "#Write#\n" );  
    char *done = "Done!";  
    int sent = send ( sock, done, 5, 0 );  
    printf ( "end\n", sent );  
}  


This is likely due to the default action of the SIGPIPE signal. To ignore this signal, use something like:

signal(SIGPIPE, SIG_IGN);

Socket errors will then be reported as return values from socket functions, rather than a signal.


Which platform is this?

On UNIX in some cases you can get a signal when the connection goes down (SIGPIPE) and this terminates the program by default... the solution is to install a signal handler for SIGPIPE that does nothing.


Try this:

sigset_t set, oldset;
sigemptyset(&set);
sigaddset(&set, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &set, &oldset);
/* use send all you like here */
sigtimedwait(&set, 0, (struct timespec [1]){0});
pthread_sigmask(SIG_SETMASK, &oldset, 0);

I'm not 100% sure it works, but I believe it should, and if it's correct then it's a solution that can be used from library code without messing up the state of the caller or other potentially-signal-using threads.

Also note that if the program (or even just the current thread) does not want to make use of SIGPIPE, you can simplify this a lot by just leaving SIGPIPE permanently blocked:

sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &set, &oldset);
0

精彩评论

暂无评论...
验证码 换一张
取 消