Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19756330
  • 博文数量: 679
  • 博客积分: 10495
  • 博客等级: 上将
  • 技术积分: 9308
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-18 10:51
文章分类

全部博文(679)

文章存档

2012年(5)

2011年(38)

2010年(86)

2009年(145)

2008年(170)

2007年(165)

2006年(89)

分类: LINUX

2008-12-02 11:07:15

§4    Linux 环境

要特别注意多任务环境下的程序。

本章考虑程序操作的环境,怎样通过环境获取操作状态,程序的的用户怎样改变行为。着重于:

*程序参数的传递

*环境变量

*获取时间

*临时文件

*获取用户和主机信息

*配置日志信息

*发现系统的限制

 

 

§4.1  程序参数

int main(int argc, char *argv[])

argc表示参数的个数,argv表示参数。Main()也可以运作,默认是intargc,argv其实依旧存在,不过没有声明,不能使用。

$ myprog left right ‘and center’

argc: 4

argv: {myprog, left, right, and center}

 

程序:

# cat args.c

#include

#include

 

int main(int argc, char *argv[])

{

    int arg;

 

    for(arg = 0; arg < argc; arg++) {

        if(argv[arg][0] == '-')

            printf("option: %s\n", argv[arg]+1);

        else

            printf("argument %d: %s\n", arg, argv[arg]);

    }

    exit(0);

}

运行结果:

$ ./args -i -lr ‘hi there’ -f fred.c

argument 0: ./args

option: i

option: lr

argument 3: hi there

option: f

argument 5: fred.c

    上面参数中-lr其实和-l –r是一样的。

         X/Open规范()定义了命令行选项(the Utility Syntax Guidelines)的标准用法,同时也定义了c程序命令行开关标准程序接口:getopt函数。

 

     Getopt

此部分尚未深刻理解

用法:

#include

int getopt(int argc, char *const argv[], const char *optstring);

extern char *optarg;

extern int optind, opterr, optopt;

 

        

实例:

# vi argopt.c

 

#include

#include

#include

 

int main(int argc, char *argv[])

{

    int opt;

 

    while((opt = getopt(argc, argv, ":if:lr")) != -1) {

        switch(opt) {

        case 'i':

        case 'l':

        case 'r':

            printf("option: %c\n", opt);

            break;

        case 'f':

            printf("filename: %s\n", optarg);

            break;

        case ':':

            printf("option needs a value\n");

            break;

        case '?':

            printf("unknown option: %c\n", optopt);

            break;

        }

    }

    for(; optind < argc; optind++)

        printf("argument: %s\n", argv[optind]);

    exit(0);

}

运行结果:

# ./argopt -i -lr ¡®hi there¡¯ -f fred.c -q

option: i

option: l

option: r

filename: fred.c

unknown option: q

argument: Hi

argument: there

 

":if:lr"表示下一个是关联参数

 

如果从选项中获取到值,存储在外部变量optarg中。

没有选项的时候,getopt返回-1--会导致getopt停止扫描选项。

遇到不认识的选项,getopt返回?,并存储在外部变量optopt中。

如果类似上面-f参数一样的需要外带一个值,却没有值,一般返回?,在第一个参数字符前添加冒号,则会返回冒号。

         外部变量optind存储下个参数的索引,一般很少使用。Getopt在不同平台的实现参见教材。

 

     getopt_long

支持长参数

暂略,参见教材

 

阅读(3548) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~