Awk bug+fix

Ken Greer kg at hplabs.UUCP
Fri Mar 2 07:49:43 AEST 1984


The following awk bug exists on all version of awk I've looked at
which includes 4.1BSD, 4.2BSD, Sys 5 rel. 0, and Sys 5 rel. 2. 

			Ken Greer
			hplabs!kg
			kg at HPLABS (CSNET)
			kg.hplabs at RAND-RELAY (ARPA)

The awk script,

END {
	print "First" > "junk"
	print "cat junk" | "sh"
	print "Second" > "junk"
    }

demonstrates two (and a half) bugs:

1) When finished, the file junk has two lines
   in it, not one.  The second > is treated like an >>.
2) The pipe on line three is executed after awk exits,
   not at the time of the call.
2.5) As a result of 1) and 2), the file cat-ed on line three
     shows two lines, not one.

The problem in awk is:

1) A file opened (with > or >>) is not closed after the
   statement is executed.  The file name is remembered
   and subsequent references to that file name use the same
   open descriptor.  (Efficient but wrong).

2) Pipes are not closed (with pclose).

The diff for the fix is:
-----------------------

In awk/run.c (procedure redirprint):

> = new version
11,16d10
< #define FILENUM	10
< struct
< {
< 	FILE *fp;
< 	char *fname;
< } files[FILENUM];
858d851
< 	register int i;
859a853
> 	FILE *fp;
863,870d856
< 	for (i=0; i<FILENUM; i++)
< 		if (strcmp(x->sval, files[i].fname) == 0)
< 			goto doit;
< 	for (i=0; i<FILENUM; i++)
< 		if (files[i].fp == 0)
< 			break;
< 	if (i >= FILENUM)
< 		error(FATAL, "too many output files %d", i);
872c858
< 		files[i].fp = popen(x->sval, "w");
---
> 		fp = popen(x->sval, "w");
874c860
< 		files[i].fp = fopen(x->sval, "a");
---
> 		fp = fopen(x->sval, "a");
876,877c862,863
< 		files[i].fp = fopen(x->sval, "w");
< 	if (files[i].fp == NULL)
---
> 		fp = fopen(x->sval, "w");
> 	if (fp == NULL)
879,884c865,869
< 	files[i].fname = tostring(x->sval);
< doit:
< 	fprintf(files[i].fp, "%s", s);
< #ifndef gcos
< 	fflush(files[i].fp);	/* in case someone is waiting for the output */
< #endif
---
> 	fprintf(fp, "%s", s);
> 	if (a == '|')
> 		pclose(fp);
> 	else
> 		fclose(fp);


-- 
Ken Greer



More information about the Comp.unix.wizards mailing list