Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang program terminates after calling linux shell command

Tags:

linux

shell

go

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.

like image 478
drdot Avatar asked Sep 07 '25 20:09

drdot


2 Answers

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

like image 171
John Weldon Avatar answered Sep 10 '25 09:09

John Weldon


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)
} 
like image 40
David Budworth Avatar answered Sep 10 '25 09:09

David Budworth