Hi. I faced a strange problem on Windows. Consider the following code:
package main
import (
"fmt"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
)
func main() {
// execute the calc
cmd := exec.Command("calc")
if err := cmd.Start(); err != nil {
fmt.Println(">>0", err)
return
}
fmt.Println("cmd.Process.Pid:", cmd.Process.Pid)
time.Sleep(2 * time.Second)
// results in `>>1 TerminateProcess: Access is denied`
if err := cmd.Process.Kill(); err != nil {
fmt.Println(">>1", err)
}
// results in `>>2 exit status 128` which means no such process
if err := exec.Command("taskkill", "/F", "/PID",
strconv.Itoa(cmd.Process.Pid)).Run(); err != nil {
fmt.Println(">>2", err)
}
// let's find the real PID by parsing tasklist output
b, _ := exec.Command("tasklist").CombinedOutput()
list := strings.Split(string(b), "\n")
var realPID int
for _, s := range list {
s = strings.ToLower(s)
if !strings.Contains(s, "calc") {
continue
}
fmt.Println("matching string:")
fmt.Println(s)
submatches :=
regexp.MustCompile(`^[\w\._\s+-]+?(\d+)`).FindStringSubmatch(s)
if len(submatches) != 2 {
fmt.Println(">>3 invalid len of submatches:", len(submatches))
return
}
var err error
realPID, err = strconv.Atoi(submatches[1])
if err != nil {
fmt.Println(">>4", err)
return
}
fmt.Println("Real PID is:", realPID)
}
cmd.Process.Pid = realPID
if err := cmd.Process.Kill(); err != nil {
fmt.Println(">>5", err)
return
}
fmt.Println("Killed: no error")
}
It launched the calc process after which tries to kill it firstly by
calling Kill() and next by calling taskkill Windows command. Both fails due
to wrong PID.
Next (for loop) we try to find the right PID manually via tasklist. After
that we assign the found PID to cmd.Process.Pid, call Kill() and it is
success.
For me this entire process produces the following output:
cmd.Process.Pid: 12704
>>1 TerminateProcess: Access is denied.
>>2 exit status 128
matching string:
calculator.exe 11316 console 1 53�284 ��
Real PID is: 11316
Killed: no error
And calc's window really appears and next disappears as the process being
killed.
Also tested Kill() on Ubuntu, it works nominal without such ugly things.
So what's the heck?
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.