Skip to content

Instantly share code, notes, and snippets.

@Jamlee
Created November 3, 2020 12:19
Show Gist options
  • Save Jamlee/6a71ba539b4537c655e6d0ddff299183 to your computer and use it in GitHub Desktop.
Save Jamlee/6a71ba539b4537c655e6d0ddff299183 to your computer and use it in GitHub Desktop.
golang: exec 时继承父级进程数据
package main
import (
"fmt"
"golang.org/x/sys/unix"
"os"
"os/exec"
"syscall"
)
var isRerun = make(map[string]int)
func Self() string {
return "/proc/self/exe"
}
func Command(args ...string) *exec.Cmd {
return &exec.Cmd{
Path: Self(),
Args: args,
SysProcAttr: &syscall.SysProcAttr{
Pdeathsig: unix.SIGTERM,
},
}
}
func main() {
// 注册
if _, exists := isRerun["flag"]; !exists {
isRerun["flag"] = 1
}
// 当前的名称不叫 flag 所以是 exists=false
fmt.Println("获取当前的flag", os.Args[0])
_, exists := isRerun[os.Args[0]]
if exists {
fmt.Printf("sec run: %s: pid is %d\n", os.Args[0], os.Getpid())
fmt.Println("goodbye")
os.Exit(0)
} else {
fmt.Printf("first run: %s: pid is %d\n", os.Args[0], os.Getpid())
}
cmd := Command("flag")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment