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) {
2829type 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
5254func 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+ }
0 commit comments