英文:
Spawn Bash Shell in Go
问题
我正在编写一个用于播放音乐的Go语言机器人,但是在让这个bash shell工作时遇到了一些问题。
proc := exec.Command("/bin/bash")
stdin, errIn := proc.StdinPipe()
stdout, errOut := proc.StdoutPipe()
WriteAndWait(stdin, stdout, "cd /home/user/bot1337/")
WriteAndWait(stdin, stdout, "rm song.mp3")
WriteAndWait(stdin, stdout, "youtube-dl --extract-audio --audio-format mp3 " + Sanitize(command[1]))
WriteAndWait(stdin, stdout, "mv *.mp3 song.mp3")
WriteAndWait(stdin, stdout, "xmms2 play song.mp3")
WriteAndWait(stdin, stdout, "quit")
WriteAndWait函数如下:
func WriteAndWait(stdout io.Writer, stdin io.Reader, command string) {
stdout.Write([]byte(command + "; echo -e '\\x63\\x68\\x65\\x63\\x6b'\r\n"))
buf := make([]byte, 256)
for {
fmt.Println("Reading...")
rlen, _ := stdin.Read(buf)
strin := string(buf[:rlen])
fmt.Println(strin)
if strings.Contains(strin, "check") {
return
}
}
}
进程被创建了,但是程序在Read()上挂起了,它无法从stdin读取任何内容。
谢谢你的帮助!
英文:
I'm writing a bot to play music in Go, and I'm having some trouble getting this bash shell to work
proc := exec.Command("/bin/bash")
stdin, errIn := proc.StdinPipe()
stdout, errOut := proc.StdoutPipe()
WriteAndWait(stdin, stdout, "cd /home/user/bot1337/")
WriteAndWait(stdin, stdout, "rm song.mp3")
WriteAndWait(stdin, stdout, "youtube-dl --extract-audio --audio-format mp3 " + Sanitize(command[1]))
WriteAndWait(stdin, stdout, "mv *.mp3 song.mp3")
WriteAndWait(stdin, stdout, "xmms2 play song.mp3")
WriteAndWait(stdin, stdout, "quit")
The WriteAndWait function
func WriteAndWait(stdout io.Writer, stdin io.Reader, command string) {
stdout.Write([]byte(command + "; echo -e '\\x63\\x68\\x65\\x63\\x6b'\r\n"))
buf := make([]byte, 256)
for {
fmt.Println("Reading...")
rlen, _ := stdin.Read(buf)
strin := string(buf[:rlen])
fmt.Println(strin)
if strings.Contains(strin, "check") {
return
}
}
}
The process gets created, but it the program hangs on Read() - it can never read anything from stdin
Thanks in advance for your help!
答案1
得分: 1
你忘记启动你的进程了。exec.Command
只是创建了进程对象,但并没有启动它。
只需在管道初始化后加上proc.Start()
,就可以解决问题了。
英文:
You forgot to start your process. exec.Command
creates the process object, but does not start it.
Just put proc.Start()
after your pipe init and it should do the trick.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论