Skip to content

Commit 1174a73

Browse files
committed
os: add ExitCode method to ProcessState
1 parent 48c7973 commit 1174a73

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

src/os/exec/exec_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,49 @@ func TestExitStatus(t *testing.T) {
168168
}
169169
}
170170

171+
func TestExitCode(t *testing.T) {
172+
// Test that exit code are returned correctly
173+
cmd := helperCommand(t, "exit", "42")
174+
cmd.Run()
175+
want := 42
176+
got := cmd.ProcessState.ExitCode()
177+
if want != got {
178+
t.Errorf("ExitCode got %d, want %d", got, want)
179+
}
180+
181+
cmd = helperCommand(t, "/no-exist-executable")
182+
cmd.Run()
183+
want = 2
184+
got = cmd.ProcessState.ExitCode()
185+
if want != got {
186+
t.Errorf("ExitCode got %d, want %d", got, want)
187+
}
188+
189+
cmd = helperCommand(t, "exit", "-1")
190+
cmd.Run()
191+
want = 255
192+
got = cmd.ProcessState.ExitCode()
193+
if want != got {
194+
t.Errorf("ExitCode got %d, want %d", got, want)
195+
}
196+
197+
cmd = helperCommand(t, "cat")
198+
cmd.Run()
199+
want = 0
200+
got = cmd.ProcessState.ExitCode()
201+
if want != got {
202+
t.Errorf("ExitCode got %d, want %d", got, want)
203+
}
204+
205+
// Test when command does not call Run().
206+
cmd = helperCommand(t, "cat")
207+
want = -1
208+
got = cmd.ProcessState.ExitCode()
209+
if want != got {
210+
t.Errorf("ExitCode got %d, want %d", got, want)
211+
}
212+
}
213+
171214
func TestPipes(t *testing.T) {
172215
check := func(what string, err error) {
173216
if err != nil {

src/os/exec_plan9.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,13 @@ func (p *ProcessState) String() string {
136136
}
137137
return "exit status: " + p.status.Msg
138138
}
139+
140+
// ExitCode returns the exit code of the exited process, or -1
141+
// if the process hasn't exited or was terminated by a signal.
142+
func (p *ProcessState) ExitCode() int {
143+
// return -1 if the process hasn't started.
144+
if p == nil {
145+
return -1
146+
}
147+
return p.status.ExitStatus()
148+
}

src/os/exec_posix.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,3 +106,13 @@ func (p *ProcessState) String() string {
106106
}
107107
return res
108108
}
109+
110+
// ExitCode returns the exit code of the exited process, or -1
111+
// if the process hasn't exited or was terminated by a signal.
112+
func (p *ProcessState) ExitCode() int {
113+
// return -1 if the process hasn't started.
114+
if p == nil {
115+
return -1
116+
}
117+
return p.status.ExitStatus()
118+
}

0 commit comments

Comments
 (0)