How to prevent SIGPIPEs (or handle them properly)

前端 未结 10 1702
名媛妹妹
名媛妹妹 2020-11-22 07:27

I have a small server program that accepts connections on a TCP or local UNIX socket, reads a simple command and (depending on the command) sends a reply.

The problem

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 07:53

    Under a modern POSIX system (i.e. Linux), you can use the sigprocmask() function.

    #include 
    
    void block_signal(int signal_to_block /* i.e. SIGPIPE */ )
    {
        sigset_t set;
        sigset_t old_state;
    
        // get the current state
        //
        sigprocmask(SIG_BLOCK, NULL, &old_state);
    
        // add signal_to_block to that existing state
        //
        set = old_state;
        sigaddset(&set, signal_to_block);
    
        // block that signal also
        //
        sigprocmask(SIG_BLOCK, &set, NULL);
    
        // ... deal with old_state if required ...
    }
    

    If you want to restore the previous state later, make sure to save the old_state somewhere safe. If you call that function multiple times, you need to either use a stack or only save the first or last old_state... or maybe have a function which removes a specific blocked signal.

    For more info read the man page.

提交回复
热议问题