Golang – 管道到外部执行

huangapple go评论76阅读模式
英文:

Golang - Pipe to external exec

问题

我正在尝试使用Go将电子邮件消息传输到sendmail二进制文件。以下代码在不取消注释Wait()调用的情况下工作。如果取消注释,程序将挂起。根据wait的文档,我得出的印象是应该调用它,因此我得出结论,我的示例代码中存在错误。有什么建议吗?

package main

import (
	"io"
	"os"
	"os/exec"
	"fmt"
)

func main() {
	msg := "From: source@email.address\n"
	msg += "To: recipient@email.address\n"
	msg += "Subject: Testing\n\n"
	msg += "Hello World!\n"
	sendmail := exec.Command("/usr/sbin/sendmail", "-t")
	stdin, err := sendmail.StdinPipe()
	if err != nil {
		panic(err)
	}
	sendmail.Stdout = os.Stdout
	sendmail.Stderr = os.Stderr
	err = sendmail.Start()
	if err != nil {
		panic(err)
	}
	io.WriteString(stdin, msg)
	//err = sendmail.Wait()
	//if err != nil {
	//	panic(err)
	//}
}
英文:

I'm trying to use Go to pipe an email message to the sendmail binary. The following code works providing I don't uncomment the call to Wait(). If it's uncommented, the program hangs. Reading the documentation for wait, I get the impression that it should be called so I'm concluding there's an error in my example code. Any suggestions for what it might be?

package main

import (
        "io"
        "os"
        "os/exec"
        "fmt"
)

func main() {
        msg := "From: source@email.address\n"
        msg += "To: recipient@email.address\n"
        msg += "Subject: Testing\n\n"
        msg += "Hello World!\n"
        sendmail := exec.Command("/usr/sbin/sendmail", "-t")
        stdin, err := sendmail.StdinPipe()
        if err != nil {
                panic(err)
        }
        sendmail.Stdout = os.Stdout
        sendmail.Stderr = os.Stderr
        err = sendmail.Start()
        if err != nil {
                panic(err)
        }
        io.WriteString(stdin, msg)
        //err = sendmail.Wait()
        //if err != nil {
        //      panic(err)
        //}
}

答案1

得分: 3

(可能)发生的情况是sendmail正在等待输入完成。

要么在写入后关闭管道,要么(根据sendmail版本和其他因素)尝试在消息的最后一部分使用“.\n”来完成发送(某些版本将接受此操作,除了关闭输入之外)。

英文:

What is (probably) happening is that sendmail is waiting for the input to finish.

Either close the pipe after having written or (depending on sendmail versions and stuff) try finishing sending through ".\n" as the very last piece of the message (some versions will accept that in addition to the input being closed).

答案2

得分: 0

永远不要在这里使用"-t"命令行选项。它会错误地发送邮件,比如将邮件列表中的消息发送回邮件列表。

英文:

NEVER NEVER NEVER use the "-t" command-line option here. It will mis-deliver mail, like sending messages from a mailing list back to the mailing list.

huangapple
  • 本文由 发表于 2014年10月24日 20:40:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/26548066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定