Skip to content

Commit

Permalink
Raise on abnormal exit in Procss::Status#exit_code (#15241)
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota authored Dec 3, 2024
1 parent 22eb886 commit 099f572
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
8 changes: 7 additions & 1 deletion spec/std/process/status_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,13 @@ describe Process::Status do
Process::Status.new(exit_status(128)).exit_code.should eq 128
Process::Status.new(exit_status(255)).exit_code.should eq 255

status_for(:interrupted).exit_code.should eq({% if flag?(:unix) %}0{% else %}LibC::STATUS_CONTROL_C_EXIT.to_i32!{% end %})
if {{ flag?(:unix) }}
expect_raises(RuntimeError, "Abnormal exit has no exit code") do
status_for(:interrupted).exit_code
end
else
status_for(:interrupted).exit_code.should eq({% if flag?(:unix) %}0{% else %}LibC::STATUS_CONTROL_C_EXIT.to_i32!{% end %})
end
end

it "#success?" do
Expand Down
12 changes: 11 additions & 1 deletion src/process/status.cr
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,19 @@ class Process::Status
{% end %}
end

# If `normal_exit?` is `true`, returns the exit code of the process.
# Returns the exit code of the process if it exited normally (`#normal_exit?`).
#
# Raises `RuntimeError` if the status describes an abnormal exit.
#
# ```
# Process.run("true").exit_code # => 1
# Process.run("exit 123", shell: true).exit_code # => 123
# Process.new("sleep", ["10"]).tap(&.terminate).wait.exit_code # RuntimeError: Abnormal exit has no exit code
# ```
def exit_code : Int32
{% if flag?(:unix) %}
raise RuntimeError.new("Abnormal exit has no exit code") unless normal_exit?

# define __WEXITSTATUS(status) (((status) & 0xff00) >> 8)
(@exit_status & 0xff00) >> 8
{% else %}
Expand Down

0 comments on commit 099f572

Please sign in to comment.