Golang程序在调用Linux shell命令后终止。

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

golang program terminates after calling linux shell command

问题

我正在以 root 权限执行以下的 Golang 程序片段:

binary, lookErr := exec.LookPath("auditctl")
if lookErr != nil {
  panic(lookErr)
}
env := os.Environ()

args := []string{"auditctl", "-D"}
execErr := syscall.Exec(binary, args, env)
if execErr != nil {
  fmt.Println("error")
  panic(execErr)
}

fmt.Println("no error")

因为系统中没有任何 auditctl 规则,所以该命令在终端中打印如下内容。这与在 shell 直接输入命令时完全正常。

No rules

但是,"error" 和 "no error" 都没有被打印出来。这意味着在 syscall.Exec 之后,Golang 程序终止了。这是怎么发生的?我该如何在 syscall.Exec 之后继续执行程序,因为我还有其他事情要在同一个程序中运行。

英文:

I am executing the following golang program (snippet) with root privilege:

  binary, lookErr := exec.LookPath("auditctl")
  if lookErr != nil {
    panic(lookErr)
  }
  env := os.Environ()

  args :=  []string{"auditctl", "-D"}
  execErr := syscall.Exec(binary, args, env)
  if execErr != nil {
    fmt.Println("error")
    panic(execErr)
  }

  fmt.Println("no error")

Because I dont have any auditctl rules in the system, the command print the following in the terminal. This is all normal just like when I type in the shell directly.

No rules

Except that neither "error" nor "no error" are printed. Which means the golang program terminates right after syscall.Exec. How did this happen and how can I continue execution after syscall.Exec because I have other things to run within the same program.

答案1

得分: 9

syscall.Exec 调用 execve(2),在Linux上不会将执行返回给调用者,而是替换当前的(Go)进程为被调用的进程。

正如David Budworth和mkopriva建议的那样,如果你真的想要在生成一个独立的进程后返回到你的Go代码中,可以考虑使用exec.Command

英文:

syscall.Exec invokes execve(2), which on linux does not return execution to the caller but replaces the current (Go) process with the process called.

As David Budworth, and mkopriva suggest.. if you actually want to spawn a separate process and return to your Go code after spawning; consider using exec.Command

答案2

得分: 3

如@mkopriva所提到的,你可能想要使用exec.Cmd。

以下是一个示例:

cmd := exec.Command("auditctl", "-D")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
if err := cmd.Run(); err != nil {
    log.Println("Failed to run auditctl:", err)
}
英文:

As @mkopriva mentioned, you probably want exec.Cmd

here's an example:

cmd := exec.Command("auditctl", "-D")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
if err := cmd.Run(); err != nil {
    log.Println("Failed to run auditctl:",err)
} 

huangapple
  • 本文由 发表于 2017年3月23日 06:12:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/42963625.html
匿名

发表评论

匿名网友

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

确定