dtpf76658 2017-04-25 12:26
浏览 145
已采纳

想要使用通道从os.Stdin写入os.Stdout

/* Want to write from os.Stdin to os.Stdout(fmt.Println() in below code) using channels*/
package main
import (
    "fmt"
    "io"
    "os"
    "bufio"
)

type message []byte
/* Function to run the groutine to run for stdin read */
func read (r io.Reader) <-chan message{
    lines := make (chan message)
    go func() {
        defer close(lines)
        scan := bufio.NewScanner(r)
        for scan.Scan() {
            lines <- message(scan.Bytes())
        }   
    }() 
    return lines
}


func main() {
    mes := make (chan message, 1)
    sig := make (chan bool)
    ch := read (os.Stdin) //Reading from Stdin
    for {
        select {
            case anu := <-mes:
                fmt.Println("Message to stdout")
                fmt.Println(string(anu)) //Writing to Stdout
            case mes <- <-ch:
                fmt.Println("Message to channel 2")
                continue
        }   
    }   
    <-sig

/*
The O/P is :

go run writetochan.go 
Golang
Message to channel 2
Fun     <<< Delayed O/P golang means after putting one more 
            message only we are getting First message
Message to stdout
Golang


Expected O/P:
go run writetochan.go 
Golang
Message to channel 2
Message to stdout
Golang
Fun
Message to channel 2

*/
}

Want to achieve the O/P shown above.

We are writing from one channel which reads all the stdin from the user and then writes to the stdout. Channel read is happening in goroutine. A dummy channel is formed (sig) so that we can run it indefinitely (Just for now).

  • 写回答

1条回答 默认 最新

  • drl959975 2017-04-25 18:35
    关注

    The problem is that you have two channel operations in your second select case. Select only prevents the outer operation from blocking. Thus the <-ch call is evaluated immediately, and doesn't have the blocking protection of the select, so the entire select statement blocks until something else is received on that channel (which requires another input so read() can send again on that channel).

    Unfortunately, the fix isn't as clean. If you change it to case m := <-ch:, then sending m over mes will block the select, and can result in a deadlock if it's already at buffer. Probably the easiest way to fix it is to only have a single channel, rather than two. Example:

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "os"
    )
    
    /* Function to run the groutine to run for stdin read */
    func read(r io.Reader) <-chan string {
        lines := make(chan string)
        go func() {
            defer close(lines)
            scan := bufio.NewScanner(r)
            for scan.Scan() {
                lines <- scan.Text()
            }
        }()
        return lines
    }
    
    func main() {
        mes := read(os.Stdin) //Reading from Stdin
        for anu := range mes {
            fmt.Println("Message to stdout")
            fmt.Println(anu) //Writing to Stdout
        }
    }
    

    Note that I changed your scan.Bytes() call to scan.Text(), because the comments for scan.Bytes() specifically state that the underlying array of the slice it returns is not safe against being overwritten by following Scan calls.

    Another alternative is to use a separate goroutine to translate the messages between the channels:

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "os"
    )
    
    /* Function to run the groutine to run for stdin read */
    func read(r io.Reader) <-chan string {
        lines := make(chan string)
        go func() {
            defer close(lines)
            scan := bufio.NewScanner(r)
            for scan.Scan() {
                s := scan.Text()
                lines <- s
            }
        }()
        return lines
    }
    
    func main() {
        mes := make(chan string, 1)
        ch := read(os.Stdin) //Reading from Stdin
        go func() {
            for m := range ch {
                fmt.Println("Message to channel 2")
                mes <- m
            }
        }()
        for anu := range mes {
            fmt.Println("Message to stdout")
            fmt.Println(anu) //Writing to Stdout
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作