Check UNIX command line arguments, pipes and redirects from C program

I have some problem to figure out how I can keep the pipe working and redirect the shell functionality as soon as I find out that the command line arguments are missing.

If I, for example, use a scanf call that will work with a redirect or pipe from a shell, but in the absence of that, I get a prompt that I don't want.

I would like to accept command line arguments via argv [], pipe, or re-direct, but I cannot figure out how to do this without receiving a prompt. If I, for example, try something like this:

if(argc < 2)
    exit(0);

      

Then the program exits if I try this:

echo arg | myProgram

      

Or that:

myProgram < fileWithArgument

      

I tried looking at this, but I always get a bash link.

+2


source to share


3 answers


A common way to handle situations like this is to check if standard input is connected to the terminal or not using isatty or similar functions depending on your OS. If so, you are taking parameters from the command line, if not (redirected), you are reading standard input.



+7


source


Short version: You can't do this.

Pipeline and redirection specifiers are not arguments to your program, rather they are caller shell commands and are processed before an executable instance of your program even exists. The shell does not pass them in to the program argv

or any other variable, and you cannot detect them in any reliable way.



Neil gave you a way to tell if you are connected to a terminal .

+2


source


In your examples, you use pipe redirection, and echo arg | myProgram

, and myProgram < filesWithArguments

send the output to your program's STDIN .

If you want to read these values, use scanf

or fread

in the STDIN file descriptor .

If you are trying to get the contents of a file as an argument list for your executable, you need to use it like this:

# This will pass `lala` as a variable
myProgram `echo lala`

      

0


source







All Articles