Skip to content

os: add ExitCode method to ProcessState #26544

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/os/exec/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,49 @@ func TestExitStatus(t *testing.T) {
}
}

func TestExitCode(t *testing.T) {
// Test that exit code are returned correctly
cmd := helperCommand(t, "exit", "42")
cmd.Run()
want := 42
got := cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}

cmd = helperCommand(t, "/no-exist-executable")
cmd.Run()
want = 2
got = cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}

cmd = helperCommand(t, "exit", "255")
cmd.Run()
want = 255
got = cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}

cmd = helperCommand(t, "cat")
cmd.Run()
want = 0
got = cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}

// Test when command does not call Run().
cmd = helperCommand(t, "cat")
want = -1
got = cmd.ProcessState.ExitCode()
if want != got {
t.Errorf("ExitCode got %d, want %d", got, want)
}
}

func TestPipes(t *testing.T) {
check := func(what string, err error) {
if err != nil {
Expand Down
10 changes: 10 additions & 0 deletions src/os/exec_plan9.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,13 @@ func (p *ProcessState) String() string {
}
return "exit status: " + p.status.Msg
}

// ExitCode returns the exit code of the exited process, or -1
// if the process hasn't exited or was terminated by a signal.
func (p *ProcessState) ExitCode() int {
// return -1 if the process hasn't started.
if p == nil {
return -1
}
return p.status.ExitStatus()
}
10 changes: 10 additions & 0 deletions src/os/exec_posix.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,13 @@ func (p *ProcessState) String() string {
}
return res
}

// ExitCode returns the exit code of the exited process, or -1
// if the process hasn't exited or was terminated by a signal.
func (p *ProcessState) ExitCode() int {
// return -1 if the process hasn't started.
if p == nil {
return -1
}
return p.status.ExitStatus()
}