Why doesn't this work (fork and pipe - (nf)

brad at bradley.UUCP brad at bradley.UUCP
Wed Jul 18 23:40:00 AEST 1984


#R:mddc:-34200:bradley:400006:000:1348
bradley!brad    Jul 18 08:40:00 1984

Below is the mod's I made to the program, the reason it didn't work
was that you had dup'ed a file descr. This now leaves two file descr.
going to the same place. When you forked you needed to close them after
the dupes. I am not sure you need to close both sides but I generally
do just to be safe.

Bradley Smith			{ihnp4,cepu,uiucdcs,noao}!bradley!brad
Bradley University
Text Processing
----------------------- 1,.d here --------------------------------
/*
 *-- Why doesn't this work ???
 *
 *	Program is supposed to execute and read the "who" processor output
 */

main()
{
	int	pipefd[2];
	int	pid;
	int	chkpid;
	char	buffer[100];


	pipe(pipefd);

	switch(pid=fork())
	{
	case -1:				/* error */
	    printf("could not fork\n");
	    exit(0);

	case 0:					/* child */
	    close(1);
	    close(pipefd[0]);
	    dup(pipefd[1]);
	    close(pipefd[1]);
	    printf("about to exec who\n");
	    execl("/bin/who", "who", (char*)0);
	    printf("could not execute\n");
	    exit(0);

	default:				/* parent */
	    close(0);
	    close(pipefd[1]);
	    dup(pipefd[0]);
	    close(pipefd[0]);

	    printf("about to read who\n");
	    while (read(0,buffer,1) == 1)
	    {
		putchar(buffer[0]);
	    }

	    printf("after who output\n");
	    while ((chkpid = wait(0)) != pid && chkpid > 0) /* null */;
	}

	printf("about to exit\n");

	exit(0);
}



More information about the Comp.unix.wizards mailing list