Last active
September 15, 2020 02:52
-
-
Save mawaldne/b20ce29405c76cdae8436ad734465813 to your computer and use it in GitHub Desktop.
Monitor a process in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"os/exec" | |
"syscall" | |
"time" | |
) | |
type Process struct { | |
cmd *exec.Cmd | |
} | |
func main() { | |
proc := &Process{cmd: nil} | |
proc.cmd = nil | |
go func() { | |
proc.cmd = exec.Command("sleep", "1") | |
err := proc.cmd.Start() | |
if err != nil { | |
log.Fatal(err) | |
panic(-1) | |
} | |
proc.cmd.Wait() | |
}() | |
for proc.cmd == nil || proc.cmd.Process == nil || proc.cmd.Process.Signal(syscall.Signal(0)) == nil { | |
log.Printf("Program is running") | |
time.Sleep(time.Duration(100) * time.Millisecond) | |
} | |
if proc.cmd.ProcessState != nil { | |
if status, ok := proc.cmd.ProcessState.Sys().(syscall.WaitStatus); ok { | |
log.Printf("Program finished with %d\n", status.ExitStatus()) | |
} | |
} else { | |
log.Print("Program finished\n") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment