How to capture os signals like ctrl+c and send the

2019-08-28 05:25发布

问题:

I am a newbie for go and websockets. I am trying to take input character by character and writing them to websocket. I even want to take ctrl+c as input and write it to websocket.

func (c *poc) writePump() {

    var err error

    exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
    exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
    defer exec.Command("stty", "-F", "/dev/tty", "echo").Run()

    var b = make([]byte, 1)
    d := make(chan os.Signal, 1)
    signal.Notify(d, os.Interrupt)

    for {
        os.Stdin.Read(b)
        err = c.ws.WriteMessage(websocket.TextMessage, b)
        if err != nil {
            log.Printf("Failed to send UTF8 char: %s", err)
        }

        go func() {
            for sig := range d {
                // ????
            }
        }()
    }
}

This code is capturing the signal but not sure how to write to websocket.

回答1:

Send a CTRL-C with

err = c.ws.WriteMessage(websocket.TextMessage, []byte{'\003'})
if err != nil {
    // handle error
}

Other useful info:

  • The printf mentions UTF-8 characters, but there's no guarantee that the byte is a valid UTF-8 character. Consider using websocket.BinaryMessage instead.

  • Use a mutex to prevent concurrent writes to the websocket connection.

  • An alternative approach is to send the signal out of band to the peer and signal the remote process.