Using pipe in linux using parent and child process

后端 未结 1 1426
自闭症患者
自闭症患者 2021-01-26 17:21

i am trying to implement this linux command using C. ls -l | cut -b 1

the way i am trying to do it is

calling ls -l in parent process putting output o

1条回答
  •  无人及你
    2021-01-26 17:58

    You didn't called the cut in the child and also the file descriptors are messed up here.

    For performing the task you have to close the stdout of parent and make the write end stdout in parent before execvp. In child you have to close stdin of child and make read end as stdin to your child before execvp. In that way your parent's stdout is stdin of your child(creating the pipe b/w two).

    int main()
    {
       int filedes[2];
       int p;
       pid_t pid = 0, pid1 = 0;
       p=pipe(filedes);
       FILE *stream;
       char buff[20];
       char *args[80];
    
       printf("pipe command returns %d, %d ,%d\n",p, filedes[0],filedes[1]);
    
       if(pipe(filedes) == -1) /* Create the pipe */
          printf("error pipe");
          pid1=fork();
          pid=getpid();
          switch (pid1) { /* Create a child process */
          case -1:
             printf("error fork"); break;
          case 0: /* Child */
          /* Close unused write end */
          /* Child can now read from pipe */
             if (close(filedes[1]) == -1)
                printf("error close");
             printf("I am a child process pid %d, and will read from pipe\n",pid);
    
             close(0); //close stdin of child
             dup(filedes[0]); //make pipes read end stdin of child
    
             args[0] = "cut";
             args[1] = "-b";
             args[2] = "1";
             args[3] = NULL;
             execvp(args[0],args);
             break;
    
             default: /* Parent */
             /* Close unused read end */
             /* Parent can now write to pipe */
             if (close(filedes[0]) == -1)
                printf("error close");
             printf("I am the parent process pid %d, and will write to pipe\n", pid );
    
             close(1); //close stdout
             dup(filedes[1]); //make write end of pipe stdout of parent
             args[0] = "ls";
             args[1] = "-l";
             args[2] = NULL;
             execvp(args[0],args);
             break;
       }
    }
    

    0 讨论(0)
提交回复
热议问题