Question

So, I have used fork() where the parent is opening a file and reading its contents into a buffer and sending the buffer from the write-end (fd[1]) to the read end (fd[0])

The child process is responsible for reading in the buffer. I want to redirect whatever is in fd[0] to stdin, so I can use Unix commands on it. To give an example:

// in child process
dup2(fd[0], 0); // 0 is STDIN 

// Don't know what to do here

execl("/bin/grep/", "grep", "hello", NULL); // find the string 'hello' and operate on the content coming from stdin

Any help would be appreciated.

Was it helpful?

Solution

It seems to be quite OK. Maybe you could close some fds after dup2:

// in child process
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);

EDIT:

There seems to be typo: "/bin/grep/"

It should be: "/bin/grep"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top