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

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

问题描述

一旦发现缺少命令行参数,我很难弄清楚如何维护 shell 的管道和重定向功能.

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 调用,它将与来自 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.

我想通过 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.

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

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