1

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?

3
  • 2
    I recommend posting a bigger part of your code than the single calls you wanted to do. Better: provide the mains of your two application with the pipe creation and the data sending, and explain what goes wrong. It would be easier helping you. ;) Commented Apr 20, 2020 at 18:02
  • Perhaps you should use popen not execvp? See, for example, Get command output in pipe, C for Linux. Commented Apr 20, 2020 at 18:19
  • 1
    If you do not want to execute the two programs in parallel and the size of the first program outputis limited use popen(cmd1, "r") for the first program and read and memorize all its output, then use popen(cmd2, "w") and write the previously memorized output. Else as you propose use fork/pipe and you do not have to save output of the first command in an array Commented Apr 20, 2020 at 18:23

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.