golang执行cmd命令行启动一个程序,然后怎么获取到这个进程的ID呢?不然就无法通过程序的方式去控制停止了,求指导!!!
更多评论
linux 下可以
```
package main
import (
"fmt"
"os"
"syscall"
)
const (
UID = 501
GUID = 100
)
func main() {
// The Credential fields are used to set UID, GID and attitional GIDS of the process
// You need to run the program as root to do this
var cred = &syscall.Credential{ UID, GUID, []uint32{} ,true}
// the Noctty flag is used to detach the process from parent tty
var sysproc = &syscall.SysProcAttr{ Credential:cred, Noctty:true }
var attr = os.ProcAttr{
Dir: ".",
Env: os.Environ(),
Files: []*os.File{
os.Stdin,
nil,
nil,
},
Sys:sysproc,
}
process, err := os.StartProcess("/bin/sleep", []string{"/bin/sleep", "100"}, &attr)
if err == nil {
fmt.Println(process.Pid)
// It is not clear from docs, but Realease actually detaches the process
err = process.Release();
if err != nil {
fmt.Println(err.Error())
}
} else {
fmt.Println(err.Error())
}
}
```
来自 stackoverflow https://stackoverflow.com/questions/23031752/start-a-process-in-go-and-detach-from-it
#1
window和Linux都试过没问题,不过话说这个看下源码不要一分钟就知道了吧,可以多多看源码的。
```go
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("ping", "www.baidu.com")
cmd.Start()
fmt.Println(cmd.Process.Pid) // 打印进程pid
//cmd.Process.Kill() // 你要的结束进程
//cmd.Process.Signal(syscall.SIGINT) // 给进程发送信号
cmd.Wait()
}
```
#2