Skip to content

Commit 2ba59fd

Browse files
committed
feat: show process pid
1 parent e494163 commit 2ba59fd

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

pkg/gobash/gobash.go

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"fmt"
99
"io"
1010
"os/exec"
11+
"strconv"
1112
"strings"
1213
)
1314

@@ -28,6 +29,7 @@ func Exec(name string, args ...string) ([]byte, error) {
2829
type Result struct {
2930
StdOut chan string
3031
Err error // If nil after the command is executed, the command is executed successfully
32+
Pid int // Process ID of the command
3133
}
3234

3335
// 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 {
5052
}
5153

5254
func handleExec(ctx context.Context, cmd *exec.Cmd, result *Result) {
53-
result.StdOut <- strings.Join(cmd.Args, " ") + "\n"
54-
5555
stdout, stderr, err := getCmdReader(cmd)
5656
if err != nil {
5757
result.Err = err
5858
return
5959
}
6060

61+
result.StdOut <- strings.Join(cmd.Args, " ") + fmt.Sprintf(" [pid]=%d", cmd.Process.Pid) + "\n" // command name and pid
62+
result.Pid = cmd.Process.Pid
63+
6164
reader := bufio.NewReader(stdout)
6265
// reads each line in real time
6366
line := ""
@@ -140,3 +143,21 @@ func getResult(cmd *exec.Cmd) ([]byte, error) {
140143

141144
return bytes, nil
142145
}
146+
147+
// ParsePid extracts the process ID from the command output string.
148+
func ParsePid(s string) int {
149+
const key = "[pid]="
150+
idx := strings.Index(s, key)
151+
if idx == -1 {
152+
return 0
153+
}
154+
155+
part := s[idx+len(key):]
156+
part = strings.TrimSpace(part)
157+
158+
pid, err := strconv.Atoi(part)
159+
if err != nil {
160+
return 0
161+
}
162+
return pid
163+
}

pkg/gobash/gobash_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,14 @@ func TestRun(t *testing.T) {
1717
for cmd, args := range cmds {
1818
ctx, _ := context.WithTimeout(context.Background(), time.Second)
1919
result := Run(ctx, cmd, args...)
20+
counter := 0
2021
for v := range result.StdOut { // Real-time output of logs and error messages
22+
counter++
23+
if counter == 1 {
24+
pid := ParsePid(v)
25+
t.Logf("pid: %d", pid)
26+
continue
27+
}
2128
t.Logf(v)
2229
}
2330
if result.Err != nil {

0 commit comments

Comments
 (0)