Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Posting-Version: version B 2.10.1 6/24/83; site mit-eddie.UUCP
Path: utzoo!watmath!clyde!cbosgd!cbdkc1!desoto!cord!hudson!bentley!hoxna!houxm!mhuxr!ulysses!allegra!mit-eddie!smh
From: smh@mit-eddie.UUCP (Steven M. Haflich)
Newsgroups: net.lang.c
Subject: Re: pipes and the sort command
Message-ID: <3363@mit-eddie.UUCP>
Date: Wed, 26-Dec-84 14:01:55 EST
Article-I.D.: mit-eddi.3363
Posted: Wed Dec 26 14:01:55 1984
Date-Received: Thu, 27-Dec-84 03:48:54 EST
References: <1650@drutx.UUCP> <6770@brl-tgr.ARPA>
Reply-To: smh@mit-eddie.UUCP (Steven M. Haflich)
Organization: MIT, Cambridge, MA
Lines: 52

>> 	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