检查UNIX命令行参数,管道和从C程序重定向 [英] Check for UNIX command line arguments, pipes and redirects from a C program

查看:239
本文介绍了检查UNIX命令行参数,管道和从C程序重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些问题要弄清楚我如何能保持管道和重定向外壳的功能,一旦我发现有丢失的命令行参数。

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.

如果我例如使用scanf函数调用,将与重新直接或从壳管工作,但在没有这个,我得到一个提示,我不想要的。

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.

我想通过的argv []接受命令行参数,管道或重新定向,但我无法弄清楚如何与出得到的提示去做。如果我例如尝试是这样的:

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. 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

或者这样:

myProgram < fileWithArgument

我也想看看这件事,但我总是得到一些bash脚本编程的参考。

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

推荐答案

要处理这种情况的常用方法是,检查标准输入流连接到终端或不使用的 isatty 或根据您的操作系统类似的功能。如果是,你把参数从命令行,如果不是(它被重定向),可以读取标准输入。

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.

这篇关于检查UNIX命令行参数,管道和从C程序重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆