Gandora
Gandora

Reputation: 368

How to redirect the output of 'ls' (or any other shell command) to a pipe?

My task is to make a program in C that opens a pipe, then one of the process' executes the ls command and writes the output into the pipe. The other process should then read it and display it in the shell.

So, the main problem I'm struggling with is this:

execl("/bin/ls", "/bin/ls", NULL);

How can I redirect the output to the pipe?

Another way I tried to do, was to redirect the output to a file, read the file and then write that to the pipe and then finally read it at the other end (and delete the file). In a shell that would like this:

ls > ls_out.txt

But I wasn't able to reproduce that with execl.

Of course my favorite solution remains something like:

execl("/bin/ls", "bin/ls", " > my_pipe", NULL)

Upvotes: 0

Views: 1926

Answers (4)

Some programmer dude
Some programmer dude

Reputation: 409356

Create a pipe in your program.

Do the fork.

In the child process make the writing end of the pipe the new STDOUT_FILENO. (Read about the dup2 system call)

Execute the program you want to run.

In the parent process read from the reading end of the pipe.

This is how e.g. popen works under the hood.

Upvotes: 1

ben
ben

Reputation: 111

I think this might be what you're looking for?

for i in ls -1; echo $i; done

or

ls -1 | xargs echo

?

Upvotes: 0

unwind
unwind

Reputation: 399959

You seem to focus on exec() a lot; that call is for running a process. The pipe must be set up before-hand, since the process you're going to start will just use whatever stdin/stdout already exists. See fork(), dup() and pipe() for the low-level primitives.

Upvotes: 0

DmitryARN
DmitryARN

Reputation: 648

Use popen() instead of execl() to read the application output, see http://linux.die.net/man/3/popen

Upvotes: 2

Related Questions