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.
source to share
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 .
source to share
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`
source to share