开发者

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

开发者 https://www.devze.com 2022-12-19 04:55 出处:网络
I have some problem to figure out how I can maintain the pipe and redirect functionality of a shell once I find out that there are missing command line arguments.

I have some problem to figure out how I can maintain the pipe and redirect functionality of a shell once I find out that there are missing command line arguments.

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

I would like to accept command line arguments through argv[], a pip开发者_如何学运维e or re-direct but I can't figure out how to do it with out getting the prompt. If I for example try something like this:

if(argc < 2)
    exit(0);

Then the program will terminate if I try this:

echo arg | myProgram

Or this:

myProgram < fileWithArgument

I have tried to look this up but I always get some bash scripting reference.


The common way to handle situations like this is to check if the standard input stream is connected to a terminal or not, using isatty or similar functions depending on your OS. If it is, you take parameters from the command line, if not (it's been redirected), you read standard input.


Short version: You can't do it.

Pipeline and redirect specifiers are not arguments to your program, rather they are commands to the invoking shell and are processed before the running instance of your program even exists. The shell does no pass them to the program in argv or any other variable, and you can not discover them in any reliable way.

Neil has given you the way to determine if you are connected to a terminal.


In your examples you are using pipe redirection, both echo arg | myProgram and myProgram < filesWithArguments are sending output to the STDIN of your program.

If you want to read these values, use scanf or fread on the STDIN file descriptor.

If you are trying to get the file content 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

精彩评论

暂无评论...
验证码 换一张
取 消