mirror of
https://github.com/zhufuyi/sponge.git
synced 2025-09-26 20:51:14 +08:00
feat: show process pid
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
@@ -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 {
|
||||
|
Reference in New Issue
Block a user