I'm now working on a small C program in Linux. Let me explain you what I want to do with a sample Linux command below
ls | grep hello
The above command is executed in the below passion (Let me know if I've got this wrong)
Now I would like to write a C program which takes the piped output of one command as input. Means, In the similar passion of how "grep" program was able to get the input from ls command (in my example above).
Similar question has been asked by another user here, but for some reason this thread has been marked as "Not a valid question"
I initially thought we can get this as a command line argument to C program. But this is not the case.
If you pipe the output from one command into another, that output will be available on the receiving process's standard input (stdin).
You can access it using the usual scanf
or fread
functions. scanf
and the like operate on stdin by default (in the same way that printf
operates on stdout by default; in the absence of a pipe, stdin is attached to the terminal), and the C standard library provides a FILE *stdin
for functions like fread
that read from a FILE stream.
POSIX also provides a STDIN_FILENO
macro in unistd.h
, for functions that operate one file descriptors instead. This will essentially always be 0, but it's bad form to rely on that being the case.
If fact, ls
and grep
starts at the same time.
ls | grep hello
means, use ls
's standard output as grep
's standard input. ls
write results to standard output, grep
waits and reads any output from standard input at once.
Still have doubts? Do an experiment. run
find / | grep usr
find /
will list all files on the computer, it should take a lot of time.
If ls
runs first, then OS gives the output to grep
, we should wait a long time with blank screen until find
finished and grep
started. But, we can see the results at once, that's a proof for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With