I am implementing pipe in C. When I try the command 'cat aa | grep "something" ' in my program. The grep process just hanging there, seems waiting for input. I don't know why. Here is the core code. Just take ExecuteCommand as simply call execve function and all arguments are correctly passed.
if ((pid = fork()) < 0)
{
perror("fork failed\n");
exit(1);
}
if (pid)
{ // parent as pipe WRITER
close(pd[0]);
close(1);
// replace input with pipe
dup(pd[1]);
// recursively call next commands
ExecuteCommand(cmds, env);
FreeCommandsArray(&cmds);
exit(0);
}
else
{ // child as pipe READER
close(pd[1]);
close(0); // close its READ end
dup(pd[0]);
ExecuteCommand(*(++splitCmds), env);
FreeCommandsArray(&cmds);
exit(0);
}
The full code is open. Another problem is I have to use the full path of the command file as the first parameter for execve (e.g. /bin/ls for ls), otherwise, I got error message, no such file existed.