简体   繁体   English

检查来自C程序的UNIX命令行参数,管道和重定向

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

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. 我有一些问题要弄清楚一旦我发现缺少命令行参数,我可以如何维护管道和重定向shell的功能。

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. 例如,如果我使用scanf调用,那将使用重定向或来自shell的管道,但如果没有这个,我会得到一个我不想要的提示。

I would like to accept command line arguments through argv[], a pipe or re-direct but I can't figure out how to do it with out getting the prompt. 我想通过argv [],管道或重定向接受命令行参数,但我无法弄清楚如何在得到提示时这样做。 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. 我试图查看这个,但我总是得到一些bash脚本参考。

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. 处理这种情况的常用方法是检查标准输入流是否连接到终端,使用isatty或类似功能,具体取决于您的操作系统。 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. 管道和重定向说明符不是程序的参数,而是它们是调用shell的命令,并且在程序的运行实例存在之前进行处理。 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. shell没有将它们传递给argv的程序或任何其他变量,并且您无法以任何可靠的方式发现它们。

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 在您的示例中,您使用管道重定向,两者都是echo arg | myProgram echo arg | myProgram and myProgram < filesWithArguments are sending output to the STDIN of your program. echo arg | myProgrammyProgram < filesWithArguments正在将输出发送到程序的STDIN

If you want to read these values, use scanf or fread on the STDIN file descriptor. 如果要读取这些值,请在STDIN文件描述符上使用scanffread

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`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM