programming unix shell piping problem
Code:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
enum
{
STDIN = 0,
STDOUT = 1,
STDERR = 2,
FD_READ = 0,
FD_WRITE = 1
};
int main(int argc, char **argv, char **envp)
{
int fd[2];
pid_t pid;
char *lessArg[] =
{
"/bin/less",
NULL
};
char *lsArg[] =
{
"/bin/ls",
NULL
}
if(0 > pipe(fd))
{
printf(%s \n", strerror(errno));
}
if( pid = fork() ) // parent
{
waitpid(pid, NULL, 0);
}
else
{
dup2(fd[FD_WRITE], STDIN);
execve("/bin/ls", lsArg, envp);
}
if( pid = fork() ) // parent
{
waitpid(pid, NULL, 0);
}
else
{
dup2(fd[FD_READ], STDIN);
execve("/bin/less", lessArg, envp);
}
return 0;
}
anyway, the code above, i'm having some trouble with. I've tried several things but i can't do what i want it to do.
What the program does is, forks ls and pipes the result into less. less is to print it out to stdout. Now that all goes fine. It prints the output, but the problem is that i can't get back my stdin. I cant quit less or move in less. I'm shut out from the keyboard to control less.
I've tried closing the file descriptors (fd) in the parent and still nothing.
If i just use file redirection with dup2 it's all fine, just when i use the pipe file descriptors is when i run into problems
thx