Obtaining process state information for a running process

4,131 views
Skip to first unread message

Paul Ruane

unread,
Mar 5, 2012, 5:21:06 AM3/5/12
to golang-nuts
I have a program that spawns a second (via os/exec.Command), waits a
bit and then checks that the spawned process has *not* exited (and
reports the error if there was one). Since updating my program to
reflect the changes in weekly.2012-02-22 this no longer works as the
Wait function I was using is gone (I now use the blocking Wait method
on Process). I've had a good look at the docs but I cannot see any way
of getting a ProcessState for a running process -- the only mechanism
for its retrieval appears to be the Wait method which waits until the
process has exited. (The ProcessState has an Exited method which makes
me suspicious that I'm missing something as, from what I can tell,
this will always be true.)

Is there any facility for querying the status of a running process?

Thanks,
Paul.

minux

unread,
Mar 5, 2012, 5:46:36 AM3/5/12
to Paul Ruane, golang-nuts
You have to use the syscall package.
This facility is removed because it is not portable among the supported OSes.

Paul Ruane

unread,
Mar 5, 2012, 6:16:38 AM3/5/12
to golang-nuts
On Mar 5, 10:46 am, minux <minux...@gmail.com> wrote:
> You have to use the syscall package.
> This facility is removed because it is not portable among the supported
> OSes.

OK, many thanks.

I guess my mistake was to convert my code to use os/Process.Wait
rather than syscall/Wait4.

Anthony Martin

unread,
Mar 5, 2012, 6:36:27 AM3/5/12
to Paul Ruane, golang-nuts

The same way you handle any blocking I/O in Go:

package main

import (
"log"
"os/exec"
"time"
)

var nwait = 1 * time.Second // vary this to see the effect

func main() {
log.SetFlags(0)

cmd := exec.Command("sleep", "2")
err := make(chan error)

// run the command and wait for it in a seperate goroutine.
go func() {
err <- cmd.Run()
}()

// sleep for a little bit.
time.Sleep(nwait)

// check the status of the process.
select {
default:
log.Print("process still running")
case e := <-err:
if e != nil {
log.Print("process exited: %s", e)
} else {
log.Print("process exited without error")
}
}
}

Cheers,
Anthony

Paul Ruane

unread,
Mar 5, 2012, 7:35:40 AM3/5/12
to golang-nuts
On Mar 5, 11:36 am, Anthony Martin <al...@pbrane.org> wrote:
>         // run the command and wait for it in a seperate goroutine.
>         go func() {
>                 err <- cmd.Run()
>         }()

Many thanks for this. Hadn't occurred to me to run it as a goroutine.

Francisco Souza

unread,
Mar 5, 2012, 11:55:02 AM3/5/12
to Paul Ruane, golang-nuts
cmd.Start()
// do whatever you want to do
err := r.Wait()
if err == nil {
    // success
}

http://weekly.golang.org/pkg/os/exec/#Cmd.Wait

--
~f
Reply all
Reply to author
Forward
0 new messages