pipes and the sort command

Steven M. Haflich smh at mit-eddie.UUCP
Thu Dec 27 05:01:55 AEST 1984


>> 	I am interested in using the popen() command to form a pipe
>> 	between my C program and the UNIX sort command. I would appreciate
>> 	any information on the best way to do this(examples would help).
>> 	I should point out that the input to the sort command would be
>> 	comming from an array and the output should be stored in an array.
>
>It is very hard to manage both ends of a piped filter from a program.
>
>Have you considered using the qsort() library routine to sort your data?

It is very hard to connect both ends of a piped filter from a single
program in the general case, but sort(I) is a special case in that it is
guaranteed not to produce output until it reads the EOF on its input.
Something like the following (untested) ought to work.  It would be
nicer if it error checked the pipe, fork, wait, and fdopen calls:

	int	pipe_to[2];
	int	pipe_fr[2];
	FILE	sortfile;
	...
	pipe(pipe_to);
	pipe(pipe_from);
	if (fork()==0) {
		close(pipe_to[1]);
		close(pipe_from[0]);
		close(0);
		close(1);
		dup(pipe_to[0]); close(pipe_to[0]);
		dup(pipe_fr[1]); close(pipe_fr[1]);
		execl("/bin/sort","sort" /* optional comma-separated
					    sort args */ , 0);
		perror("Can't exec /bin/sort");
		exit(-1);
	}
	close(pipe_to[0]); close(pipe_fr[1]);
	sortfile = fdopen(pipe_to[1],"w");
	/* Code to write data to the sort program goes here, e.g.:
	for (i=0; i<arraydim; i++)
		fprintf(sortfile,"%d\n",array[i]);
	*/
	fclose(sortfile);
	sortfile = fdopen(pipe_from[0],"r");
	/* Code to read data back from the sort goes here, e.g.:
	   Note that this code doesn't make use of the fact that sort
	   necessarily returns the same number of items as written.
	for (i=0; fscanf(sortfile,"%d\n",&array[i]) == 1; i++);
	*/
	fclose(sortfile);
	wait(0);

Hope this helps.  It isn't nearly so confusing as it looks, provided
I typed it extempore without errors.



More information about the Comp.lang.c mailing list