0

I try to get the output of the execvp and print it to a named pipe. But how can I do this? Here is my code :

    void *run(void *comm)
{
   struct command *com = (struct command *)comm;
   int fd[2];
   pipe(fd);

   if (fork() == 0)
   {
      close(fd[0]);

      dup2(fd[1], 1);
      dup2(fd[1], 2);
      close(fd[1]);

      execvp(com->list[0], com->list);
   }
   else
   {
      char buffer[1024] = {0};

      close(fd[1]);
      unlink(com->namePipe);
      if(mkfifo(com->namePipe, 0644) != 0)
      {
          fprintf(stderr, "Impossible de créer le tube nommé.\n");
          exit(EXIT_FAILURE);
      }
      if((fd[0] = open(com->namePipe, O_WRONLY)) == -1)
      {
          fprintf(stderr, "Impossible d'ouvrir l'entrée du tube nommé.\n");
          exit(EXIT_FAILURE);
      }
      while (read(fd[0], buffer, sizeof(buffer)) != 0)
      {
         write(1, buffer, strlen(buffer));
         memset (buffer, 0, sizeof(buffer));
      }
   }
    return NULL;

}

I'm not allowed to use popen.

EDIT : I did this but not work ^^

  • Do you really want _to get the output of the execvp_ through an ordinary pipe and afterwards _print it to a named pipe_, or rather _get the output of the execvp_ through _a named pipe_? – Armali Apr 17 '18 at 12:31

2 Answers2

1
*fd = pipe_fds[0];

Here, you dereference the pointer fd, but you never assign a value to fd so its contents are indeterminate. Attempting to dereference an uninitialized pointer leads to undefined behavior.

You really don't even need a pointer here. Just declare fd as an int and assign it directly.

int fd;
...
fd = pipe_fds[0];

Once you do this, you can use read to read from fd to get the program's output.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

Here is an example of how to get the output of a command (with execl):

#include <unistd.h>
#include <string.h>

int main()
{
   int fd[2];
   pipe(fd);

   if (fork() == 0)
   {
      close(fd[0]);

      dup2(fd[1], 1);
      dup2(fd[1], 2);
      close(fd[1]);

      execl("/bin/sh", "sh", "-c", "a_binary", (char *)NULL);
   }
   else
   {
      char buffer[1024] = {0};

      close(fd[1]);

      while (read(fd[0], buffer, sizeof(buffer)) != 0)
      {
         write(1, buffer, strlen(buffer));
         memset (buffer, 0, sizeof(buffer));
      }
   }
   return 0;
}
Eliot B.
  • 162
  • 11