0

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396
Hengstar
  • 180
  • 2
  • 13
  • Are you sure you should call `exit()` in the parent process? Do you have another `fork()` call you don't show? – Some programmer dude Sep 21 '15 at 06:37
  • yes, if you go into the full code, you should see it is already a fork before going here – Hengstar Sep 21 '15 at 06:38
  • "Just take ExecuteCommand as simply call execve function and all arguments are correctly passed." -- you'd have to prove that. Please reduce the code so you can post it in a compilable version here exhibiting the undesired behaviour. Btw, I'd call it *using* pipes ... –  Sep 21 '15 at 06:54

1 Answers1

0

It is the quotation mark at the first argument of grep cause the problem. It works well if I get rid of it on input. e.g 'cat aa | grep drw' instead of 'cat aa | grep "something"'

Hengstar
  • 180
  • 2
  • 13
  • although the output is correct, the grep process seems never stop running before the main process die. – Hengstar Sep 21 '15 at 08:52