Pulpit
Pulpit

Reputation: 95

How to save output of a command in char array in c?

I need to make 2 programs communicating with each other using pipes. First program save's it's path in a pipe and sends it to second, which should run ls command with that path and send back the output of ls. I wanted to send like this write(fd2, arr2, strlen(arr2)+1); where fd2 is is an integer that contains descriptor. I wanted to execvp("ls ", argv); and assign it's output to arr2, but i don't know how to do this without additions files.

EDIT

Basically the problem is:

How to save the output of execvp("ls ", argv); in an array?

Upvotes: 1

Views: 533

Answers (1)

Aneri
Aneri

Reputation: 1352

execvp doesn't have an output value (as the fact of returning from an exec function is an indication of an error).

If you want to have only the output, use popen.

If you want more control (or want to redirect both in and out), read on.

Assuming you want to grab the output of a program you run in exec, you need to do the following:

  • Make a pipe (use pipe())
  • fork()
  • In one of the processes (usually, child):
    • Set the descriptors so that 1 points to a writing end of a pipe (use dup2)
    • Close the reading end of the same pipe and the other writing end
    • exec()
  • In the other process (usually, parent):
    • Close the writing end of the pipe
    • Read from the reading end of the pipe until it's closed from the writing end
    • Wait for the child to exit (note that closed pipe does not equate a terminated process)
    • Use whatever you have read from the pipe.

Upvotes: 1

Related Questions