5.9.1 Using close()’s Return Value

In many older versions of Unix awk, the close() function is actually a statement. (d.c.) It is a syntax error to try and use the return value from close():

command = "..."
command | getline info
retval = close(command)  # syntax error in many Unix awks

gawk treats close() as a function. The return value is −1 if the argument names something that was never opened with a redirection, or if there is a system problem closing the file or process. In these cases, gawk sets the predefined variable ERRNO to a string describing the problem.

In gawk, starting with version 4.2, when closing a pipe or coprocess (input or output), the return value is the exit status of the command, as described in Table 5.1.31 Otherwise, it is the return value from the system’s close() or fclose() C functions when closing input or output files, respectively. This value is zero if the close succeeds, or −1 if it fails. Recent versions of BWK awk also return the same values from close().

SituationReturn value from close()
Normal exit of commandCommand’s exit status
Death by signal of command256 + number of murderous signal
Death by signal of command with core dump512 + number of murderous signal
Some kind of error−1

Table 5.1: Return values from close() of a pipe

The POSIX standard is very vague; it says that close() returns zero on success and a nonzero value otherwise. In general, different implementations vary in what they report when closing pipes; thus, the return value cannot be used portably. (d.c.) In POSIX mode (see Command-Line Options), gawk just returns zero when closing a pipe.


Footnotes

(31)

Prior to version 4.2, the return value from closing a pipe or co-process was the full 16-bit exit value as defined by the wait() system call.