Writing to a closed, local TCP socket not failing

后端 未结 5 1136
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 21:10

I seem to be having a problem with my sockets. Below, you will see some code which forks a server and a client. The server opens a TCP socket, and the client connects to i

5条回答
  •  没有蜡笔的小新
    2020-11-29 21:50

    After having called write() one (first) time (as coded in your example) after the client close()ed the socket, you'll be getting the expected EPIPE and SIGPIPE on any successive call to write().

    Just try adding another write() to provoke the error:

    ...
    printf( "Errno before: %s\n", strerror( errno ) );
    printf( "Write result: %d\n", write( client_fd, "123", 3 ) );
    printf( "Errno after:  %s\n", strerror( errno ) );
    
    printf( "Errno before: %s\n", strerror( errno ) );
    printf( "Write result: %d\n", write( client_fd, "A", 1 ) );
    printf( "Errno after:  %s\n", strerror( errno ) );
    ...
    

    The output will be:

    Accepting
    Server sleeping
    Client closing its fd... Client exiting.
    Errno before: Success
    Write result: 3
    Errno after:  Success
    Errno before: Success
    Client status is 0, server status is 13
    

    The output of the last two printf()s is missing as the process terminates due to SIGPIPE being raised by the second call to write(). To avoid the termination of the process, you might like to make the process ignore SIGPIPE.

提交回复
热议问题