Hello,
I want to redirect stdin and stdout of "cat" program to my program.
For example if I type "cat" in terminal, and enter input and press enter it outputs the same string I entered.
In my c program I am trying to use pipes and dup. I cannot figure out why it is not working.
When I launch it, it exits without reading stdout of "cat".

Here is what I have so far:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#define STDIN fileno(stdin)
#define STDOUT fileno(stdout)
#define STDERR fileno(stderr)

int main(int argc, char *argv[]){

	int p2c[2] = {-1, -1};  /* parent -> child */
	int c2p[2] = {-1, -1};  /* child -> parent */
	pid_t childpid; /* child process id */

	if (pipe(p2c) < 0 || pipe(c2p)){
		/* Error establishing pipes */
	} else {

#define CHILDREAD  p2c[0]
#define CHILDWRITE c2p[1]
#define PARENTREAD c2p[0]
#define PARENTWRITE p2c[1]

		childpid = fork();
		if (childpid == 0) {
			/* Child process */
			close(PARENTWRITE); 
			close(PARENTREAD);
			dup2(CHILDREAD, STDIN);
			dup2(CHILDWRITE, STDOUT);
			close(CHILDREAD);
			close(CHILDWRITE);
			execv("cat", NULL);
		} else {
			/* Parent process */
			close(CHILDREAD); close(CHILDWRITE);
			char *writing = "BLAHHHHH\n";
			char *reading = calloc(strlen(writing), sizeof(char));
			write(PARENTWRITE, writing, strlen(writing));
			
			read(PARENTWRITE, reading, strlen(reading));
			printf("Parent read from child: %s\n",reading);
			close(PARENTWRITE); close(PARENTREAD);	
			wait(NULL);		
		}
	}
	
	return 0;
}

Thanks for your help!!!

This article has been dead for over six months. Start a new discussion instead.