Next: , Previous: , Up: Printing   [Contents][Index]


5.10 Enabling Nonfatal Output

This section describes a gawk-specific feature.

In standard awk, output with print or printf to a nonexistent file, or some other I/O error (such as filling up the disk) is a fatal error.

$ gawk 'BEGIN { print "hi" > "/no/such/file" }'
error→ gawk: cmd. line:1: fatal: can't redirect to `/no/such/file' (No
error→ such file or directory)

gawk makes it possible to detect that an error has occurred, allowing you to possibly recover from the error, or at least print an error message of your choosing before exiting. You can do this in one of two ways:

Once you have enabled nonfatal output, you must check ERRNO after every relevant print or printf statement to see if something went wrong. It is also a good idea to initialize ERRNO to zero before attempting the output. For example:

$ gawk '
> BEGIN {
>     PROCINFO["NONFATAL"] = 1
>     ERRNO = 0
>     print "hi" > "/no/such/file"
>     if (ERRNO) {
>         print("Output failed:", ERRNO) > "/dev/stderr"
>         exit 1
>     }
> }'
error→ Output failed: No such file or directory

Here, gawk did not produce a fatal error; instead it let the awk program code detect the problem and handle it.

This mechanism works also for standard output and standard error. For standard output, you may use PROCINFO["-", "NONFATAL"] or PROCINFO["/dev/stdout", "NONFATAL"]. For standard error, use PROCINFO["/dev/stderr", "NONFATAL"].

When attempting to open a TCP/IP socket (see section Using gawk for Network Programming), gawk tries multiple times. The GAWK_SOCK_RETRIES environment variable (see section Other Environment Variables) allows you to override gawk’s builtin default number of attempts. However, once nonfatal I/O is enabled for a given socket, gawk only retries once, relying on awk-level code to notice that there was a problem.


Next: , Previous: , Up: Printing   [Contents][Index]