21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

170 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>10.2 Two-Way Communications with Another ProcessFrom: brennan@whidbey.com (Mike Brennan)Newsgroups: comp.lang.awkSubject: Re: Learn the SECRET to Attract Women EasilyDate: 4 Aug 1997 17:34:46 GMTMessage-ID: On 3 Aug 1997 13:17:43 GMT, Want More Dates??? wrote:>Learn the SECRET to Attract Women Easily>>The SCENT(tm) Pheromone Sex Attractant For Men to Attract WomenThe scent of awk programmers is a lot more attractive to women thanthe scent of perl programmers.--Mike BrennanIt is often useful to be able to send data to a separate program for processing and thenread the result. This can always be done with temporary files:# write the data for processingtempfile = ("mydata." PROCINFO["pid"])while (not done with data)print data | ("subprogram > " tempfile)close("subprogram > " tempfile)# read the results, remove tempfile when donewhile ((getline newdata < tempfile) > 0)process newdata appropriatelyclose(tempfile)system("rm " tempfile)This works, but not elegantly. Among other things, it requires that the program be run ina directory that cannot be shared among users; for example, ‘/tmp’ will not do, as anotheruser might happen to be using a temporary file with the same name.Starting with version 3.1 of gawk, it is possible to open a two-way pipe to another process.The second process is termed a coprocess, since it runs in parallel with gawk. The two-wayconnection is created using the new ‘|&’ operator (borrowed from the Korn shell, ksh): 1do {print data |& "subprogram""subprogram" |& getline results} while (data left to process)close("subprogram")The first time an I/O operation is executed using the ‘|&’ operator, gawk creates a twowaypipeline to a child process that runs the other program. Output created with printor printf is written to the program’s standard input, and output from the program’sstandard output can be read by the gawk program using getline. As is the case withprocesses started by ‘|’, the subprogram can be any program, or pipeline of programs, thatcan be started by the shell.1 This is very different from the same operator in the C shell, csh.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!