17.4.13 Accessing and Manipulating Redirections

The following function allows extensions to access and manipulate redirections.

awk_bool_t get_file(const char *name,
                    size_t name_len,
                    const char *filetype,
                    int fd,
                    const awk_input_buf_t **ibufp,
                    const awk_output_buf_t **obufp);

Look up file name in gawk’s internal redirection table. If name is NULL or name_len is zero, return data for the currently open input file corresponding to FILENAME. (This does not access the filetype argument, so that may be undefined). If the file is not already open, attempt to open it. The filetype argument must be zero-terminated and should be one of:

">"

A file opened for output.

">>"

A file opened for append.

"<"

A file opened for input.

"|>"

A pipe opened for output.

"|<"

A pipe opened for input.

"|&"

A two-way coprocess.

On error, return awk_false. Otherwise, return awk_true, and return additional information about the redirection in the ibufp and obufp pointers.

For input redirections, the *ibufp value should be non-NULL, and *obufp should be NULL. For output redirections, the *obufp value should be non-NULL, and *ibufp should be NULL. For two-way coprocesses, both values should be non-NULL.

In the usual case, the extension is interested in (*ibufp)->fd and/or fileno((*obufp)->fp). If the file is not already open, and the fd argument is nonnegative, gawk will use that file descriptor instead of opening the file in the usual way. If fd is nonnegative, but the file exists already, gawk ignores fd and returns the existing file. It is the caller’s responsibility to notice that neither the fd in the returned awk_input_buf_t nor the fd in the returned awk_output_buf_t matches the requested value.

Note that supplying a file descriptor is currently not supported for pipes. However, supplying a file descriptor should work for input, output, append, and two-way (coprocess) sockets. If filetype is two-way, gawk assumes that it is a socket! Note that in the two-way case, the input and output file descriptors may differ. To check for success, you must check whether either matches.

It is anticipated that this API function will be used to implement I/O multiplexing and a socket library.