benhoyt/goawk

system() always returns -1 if process exits due to signal

juster opened this issue · 0 comments

juster commented

Another incompatible feature of awks is the return value of system() when death by signal is involved. The POSIX standard stipulates that the results of awk's system() should be the value of C's system(3) (which is the value of waitpid(2)). But due to possible human error the value of awk's system() on signal exit was originally a fraction! This is C's waitpid(2) result divided by 256.

The source here is goawk's system() docs:

On POSIX systems, a command’s exit status is a 16-bit number. The exit value passed to the C exit() function is held in the high-order eight bits. The low-order bits indicate if the process was killed by a signal (bit 7) and if so, the guilty signal number (bits 0–6).

Traditionally, awk’s system() function has simply returned the exit status value divided by 256. In the normal case this gives the exit status but in the case of death-by-signal it yields a fractional floating-point value.52 POSIX states that awk’s system() should return the full 16-bit value.

gawk steers a middle ground. The return values are summarized in Table 9.5.

Example test command

goawk 'BEGIN { print system("kill -1 $$") }'

awk variant output

Variant Output Matches close(pipe)? Comment
goawk -1 N Any signal always causes -1
lucent 0.00390625 N 1 / 256
nawk " " "
gawk 257 Y 256 + 1
mawk " " "
POSIX standard 1 N Result of waitpid()

Summary

There is no right answer. You could be the first awk to implement the POSIX standard ;) but I would suggest following gawk's example.

Another nice thing gawk did was to make the result the same as close() on a command pipe. Original awk behavior isn't terrible here but it forgets to match system() with the close() on a pipe. This may be due to the fact that using the close() result on pipe was not implemented in original awk.

I stumbled across this when matching gawk's behavior for #203. I will make both close(pipe) and system() match gawk's result in my forked branch, for now.