feat: show process pid

This commit is contained in:
zhuyasen
2025-09-06 15:41:16 +08:00
parent e494163eab
commit 2ba59fdf8b
2 changed files with 30 additions and 2 deletions

View File

@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"os/exec"
"strconv"
"strings"
)
@@ -28,6 +29,7 @@ func Exec(name string, args ...string) ([]byte, error) {
type Result struct {
StdOut chan string
Err error // If nil after the command is executed, the command is executed successfully
Pid int // Process ID of the command
}
// Run execute the command, no execution, command name must be in system path,
@@ -50,14 +52,15 @@ func Run(ctx context.Context, name string, args ...string) *Result {
}
func handleExec(ctx context.Context, cmd *exec.Cmd, result *Result) {
result.StdOut <- strings.Join(cmd.Args, " ") + "\n"
stdout, stderr, err := getCmdReader(cmd)
if err != nil {
result.Err = err
return
}
result.StdOut <- strings.Join(cmd.Args, " ") + fmt.Sprintf(" [pid]=%d", cmd.Process.Pid) + "\n" // command name and pid
result.Pid = cmd.Process.Pid
reader := bufio.NewReader(stdout)
// reads each line in real time
line := ""
@@ -140,3 +143,21 @@ func getResult(cmd *exec.Cmd) ([]byte, error) {
return bytes, nil
}
// ParsePid extracts the process ID from the command output string.
func ParsePid(s string) int {
const key = "[pid]="
idx := strings.Index(s, key)
if idx == -1 {
return 0
}
part := s[idx+len(key):]
part = strings.TrimSpace(part)
pid, err := strconv.Atoi(part)
if err != nil {
return 0
}
return pid
}

View File

@@ -17,7 +17,14 @@ func TestRun(t *testing.T) {
for cmd, args := range cmds {
ctx, _ := context.WithTimeout(context.Background(), time.Second)
result := Run(ctx, cmd, args...)
counter := 0
for v := range result.StdOut { // Real-time output of logs and error messages
counter++
if counter == 1 {
pid := ParsePid(v)
t.Logf("pid: %d", pid)
continue
}
t.Logf(v)
}
if result.Err != nil {