Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another Linux command output (Piped) as input to my C program

Tags:

c

pipe

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)

  1. ls command will be executed first
  2. Output will be given to grep command which will again generate output by matching "hello"

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.

like image 824
Santhosh Reddy Mandadi Avatar asked Oct 04 '22 23:10

Santhosh Reddy Mandadi


2 Answers

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.

like image 74
Cairnarvon Avatar answered Oct 11 '22 11:10

Cairnarvon


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.

like image 40
比尔盖子 Avatar answered Oct 11 '22 12:10

比尔盖子