等待一个非子进程结束

Hi I am working on a simple code that will monitor a process and restart the process in case the process crashes. I have written a small sample code.

This is my external process

package main

import (
    "fmt"
    "time"
)

func main() {
    for {
        time.Sleep(1000 * time.Millisecond)
        fmt.Println("hello")
    }
}

This is the code that monitors it.

package main

import (
    "fmt"
    "os"
)

func main() {
    p, e := os.FindProcess(<processid>)
    fmt.Println(e)
    fmt.Println(p.Wait())
    fmt.Println("done")
}

The challenge here is that since the first process is not a child process of the second one, it does not wait and directly exits. Please let me know if anyone has any ideas around this.

Thanks.

doushi7314
doushi7314 您是否尝试过使用Go-PS?github.com/mitchellh/go-ps还是gops?github.com/google/gops
大约 3 年之前 回复

1个回答



监视进程退出,因为 p.Wait()</ code>不阻塞。</ p>

文档:</ p>


在大多数操作系统上,该进程必须是当前进程的子进程,否则将返回错误。</ p>
</ blockquote>

您也许可以 轮询进程池以检查该进程是否仍然存在。</ p>
</ div>

展开原文

原文

Monitoring process exits because p.Wait() does not block.

From the docs:

On most operating systems, the Process must be a child of the current process or an error will be returned.

You can perhaps poll the process pool to check if the process still exists.

doukan4039
doukan4039 您可以尝试上面评论中列出的软件包之一。 例如,使用go-ps并让循环间歇地检查进程可执行文件,以查看进程是否仍在运行。 管道可能很复杂,但它们将是更好的解决方案。
大约 3 年之前 回复
douchun6108
douchun6108 您知道轮询的任何机制吗,管道是一种解决方法,但您想实施一个不太复杂的解决方案
大约 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐