On 2020-09-10, Frederick Gotham <
cauldwel...@gmail.com> wrote:
> I wonder if I'm missing something here though, because when I do a web search on how to analyse the return value from "system" on Linux, I see people do this:
>
> if ( (status < 0) && WIFEXITED(status) && EXIT_SUCCESS == WEXITSTATUS(status) )
> {
> puts("grep succeeded");
> }
>
> I don't see why they're checking for "less than zero" like that instead of checking for -1. This seems to be quite common on sites like Stack Overflow.
That looks like buggy nonsense. In the expected case when the command exits
normally with a successful termination status, system returns precisely zero,
which is not less than zero.
I can explore some of the usual behaviors quickly via FFI in TXR Lisp though
not the -1 case whereby fork fails:
This is the TXR Lisp interactive listener of TXR 243.
Quit with :quit or Ctrl-D on an empty line. Ctrl-X ? for cheatsheet.
1> (with-dyn-lib nil
(deffi system "system" int (str)))
#:lib-0009
Basic test:
2> (system "echo working")
working
0
Try the true builtin:
3> (system "true")
0
False:
4> (system "false")
256
Nonexistent program:
5> (system "/usr/bin/nonexistent")
sh: 1: /usr/bin/nonexistent: not found
32512
Bad shell syntax:
6> (system "(badshellsyntax ")
sh: 1: Syntax error: end of file unexpected (expecting ")")
512
In the nonexistent program case, the termination status is 127:
7> (w-ifexited 32512)
t
8> (w-ifsignaled 32512)
nil
9> (w-exitstatus 32512)
127
What status is the 512 status value from bad syntax:
10> (w-exitstatus 512)
2
Check that system(NULL) returns nonzero to indicate that the interpreter is
available:
11> (system nil)
1
As you can see, the failed exit statuses are positive.
That might not be the case for all possible failed exit statuses. However, on
Linux, the status word is just 16 bits. Values of the termination status above
255 are truncated:
12> (system "exit 255")
65280
13> (system "exit 65535")
65280
I don't think that any manner of termination uses any higher bits than 16 on
Linux, so there are only positive values.
Still, I would check for the exact value of -1, as you are doing, and not
assume that any negative value means that creating the child process failed.