Go wait4 function

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

Go wait4 function

问题

我可以为您提供一个在Go语言中使用wait4函数的简单示例:

package main

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

func main() {
	cmd := exec.Command("ls", "-l") // 创建一个命令

	if err := cmd.Start(); err != nil { // 启动命令
		fmt.Printf("启动命令失败:%v\n", err)
		os.Exit(1)
	}

	// 等待命令执行完成并获取状态
	var status syscall.WaitStatus
	if _, err := syscall.Wait4(cmd.Process.Pid, &status, 0, nil); err != nil {
		fmt.Printf("等待命令完成失败:%v\n", err)
		os.Exit(1)
	}

	// 打印命令的退出状态
	fmt.Printf("命令退出状态:%d\n", status.ExitStatus())
}

在这个示例中,我们使用exec.Command函数创建一个命令,并使用cmd.Start()启动它。然后,我们使用syscall.Wait4函数等待命令执行完成,并获取命令的退出状态。最后,我们打印命令的退出状态。

请注意,这只是一个简单的示例,您可以根据自己的需求进行修改和扩展。

英文:

I want to test wait4 function, but I'm not really familiar with child processes and so on, but I need to keep it working and during this time send it some signal and see reaction. Can you give me a little example of using wait4 in Go?

答案1

得分: 2

wait4在Linux上已经被弃用,正确的方法是使用exec.Command并调用.Wait()

一个带有信号的示例:

func bgProcess(app string) (chan error, *os.Process, error) {
    cmd := exec.Command(app)
    ch := make(chan error, 1)
    if err := cmd.Start(); err != nil {
        return nil, nil, err
    }
    go func() {
        ch <- cmd.Wait()
    }()
    return ch, cmd.Process, nil
}
func main() {
    ch, proc, err := bgProcess("/usr/bin/cat")
    if err != nil {
        log.Fatal(err)
    }
    log.Println("Signal(os.Kill):", proc.Signal(os.Kill))
    log.Println("cat returned:", <-ch)

}
英文:

wait4 is deprecated on Linux, the proper way is to use exec.Command and call .Wait().

An example with signals:

func bgProcess(app string) (chan error, *os.Process, error) {
	cmd := exec.Command(app)
	ch := make(chan error, 1)
	if err := cmd.Start(); err != nil {
		return nil, nil, err
	}
	go func() {
		ch &lt;- cmd.Wait()
	}()
	return ch, cmd.Process, nil
}
func main() {
	ch, proc, err := bgProcess(&quot;/usr/bin/cat&quot;)
	if err != nil {
		log.Fatal(err)
	}
	log.Println(&quot;Signal(os.Kill):&quot;, proc.Signal(os.Kill))
	log.Println(&quot;cat returned:&quot;, &lt;-ch)

}

huangapple
  • 本文由 发表于 2015年8月11日 20:44:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/31942171.html
匿名

发表评论

匿名网友

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

确定