0

I need to create a new process to run the xxx program, load the xxx program, send 'xxx' the data read from a pipe, but I'm getting this error, "Error: could not read from stdin" whenever I try to compile.

pid_t pid;
pid = fork();
int fd[2]; 
int ret;

ret = pipe(fd); 

if (ret == -1)
{
    perror("pipe failed");
    exit(1);
}

if (pid == -1)
{
    perror("fork failed");
    exit(1);
}

else if (pid == 0) //Child
{
    char buff[10];
    int validate;
    close(fd[1]);
    dup2(fd[0], STDIN_FILENO); 
    close(fd[0]);
    read(STDIN_FILENO, buff, sizeof(buff)); 
    xxx = execlp("./xxx", "./xxx", NULL); //run xxx
    exit(validate);
}

else //Parent //WRITE STDIN TO PIPE
{
    close(fd[0]); 



    //writes data to pipe



    close(fd[1]);

Help would be much appreciated!

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
user3291818
  • 203
  • 1
  • 3
  • 11
  • if you provide minimum compilable code, you can get more help from engineers. – Whoami Mar 07 '14 at 08:28
  • Why are you reading from the pipe before calling `execlp`? That will cause the exec'ed program to skip the first 10 bytes in the pipe. – Barmar Mar 07 '14 at 08:40

3 Answers3

0

You need to create the pipe before the fork!

Here is the code + fix of how it should be done C pipe, fork, dup, and exec()

Community
  • 1
  • 1
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

Could you please elaborate more on what you are trying to do? One thing that is wrong here is you are calling the pipe() call after the fork, causing the parent as well as the child to have different copies of the file descriptors. You should create the pipe before the fork() call so that the two processes share the pipe.

StackSmasher
  • 359
  • 1
  • 3
  • 6
0

First of all: you have to call pipe before fork, otherwise there will be NO communication between processes.

Secondly: Your read before execlp does not have any sense, because you are not using information stored in buff anywhere. This one you'll have to explain to get any more help.

Also close stdin before calling dup.

zoska
  • 1,684
  • 11
  • 23