Next: , Previous: Gawk Special Files, Up: Using Networking



2.2 Establishing a TCP Connection

Let's observe a network connection at work. Type in the following program and watch the output. Within a second, it connects via TCP (/inet/tcp) to the machine it is running on (`localhost') and asks the service `daytime' on the machine what time it is:

     BEGIN {
       "/inet/tcp/0/localhost/daytime" |& getline
       print $0
       close("/inet/tcp/0/localhost/daytime")
     }

Even experienced awk users will find the second line strange in two respects:

The `|&' operator was introduced in gawk 3.1 in order to overcome the crucial restriction that access to files and pipes in awk is always unidirectional. It was formerly impossible to use both access modes on the same file or pipe. Instead of changing the whole concept of file access, the `|&' operator behaves exactly like the usual pipe operator except for two additions:

In the earlier example, the `|&' operator tells getline to read a line from the special file /inet/tcp/0/localhost/daytime. We could also have printed a line into the special file. But instead we just read a line with the time, printed it, and closed the connection. (While we could just let gawk close the connection by finishing the program, in this web page we are pedantic and always explicitly close the connections.)