Exec/Fork/Stdout (Eek! Help!)

M.D. Srinivas Murthy murthy at la.excelan.com
Tue Jul 31 06:37:36 AEST 1990


In article <7890 at ucrmath.ucr.edu> yakker at ucrmath.ucr.edu (matt robinson) writes:
>
>fork off a child process, exec the process, and send the data
>from stdout/stderr back to the parent, and produce it into
>a window.  Now, the hard part about this is that I'M LOST! :)
>

Here is a small program which forks a child and captures the stdout and stderr
of child with one descriptor :

------------------------- Cut here --------------------------------------
#include <stdio.h>

main()
{
	int fd[2] ;
	char buf[80];
	int ch ;

	pipe(fd);

	if ( fork() ) {
		close(fd[1]);
		memset(buf,0,80);
		while(read(fd[0],buf,80)) {
			printf("read: %s\n",buf);
			memset(buf,0,80);
		}
	}
	else {
		close(fd[0]);
		close(1);
		close(2);
		dup(fd[1]);
		dup(fd[1]);
		close(fd[1]);
		printf("Child writing to stdout\n");
		fflush(stdout) ;
		fprintf(stderr,"Child writing to stderr\n");
		fflush(stderr) ;
	}
}

---------------------- End --------------------------------------------

however, note that the stderr and stdout of the child may get intermingled.
Of course you can open two pipes and keep the stderr and stdout separate.

if you want to exec a program in the child, you can do it after the stdout
and stderr are mapped to the pipe communicating with the parent.



More information about the Comp.unix.questions mailing list