LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 940|回复: 4

文件描述符和输入输出重定向的问题

[复制链接]
发表于 2009-5-25 22:43:40 | 显示全部楼层 |阅读模式
这是《Unix 环境高级编程》中的一个例子的运行结果。
有这本书的可以看3.14节。
a.out接受一个参数,该参数是一个文件描述符,打印该描述符的文件标志说明。
如是只读还是读写等等。
疑惑的是为何能这样运行?
    $ ./a.out 0 < /dev/tty
    read only
    $ ./a.out 1 > temp.foo
    $ cat temp.foo
    write only
    $ ./a.out 2 2>>temp.foo
    write only, append
    $ ./a.out 5 5 <>temp.foo
    read write
希望能解释一下上面四个是怎么运行的.
发表于 2009-5-26 10:26:25 | 显示全部楼层
建议 贴源码
回复 支持 反对

使用道具 举报

发表于 2009-5-26 12:34:37 | 显示全部楼层
程序运行时,sys会默认打开几个fd,比如标准输入之类。。。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-5-27 07:34:19 | 显示全部楼层
#include "apue.h"
#include <fcntl.h>
int
main(int argc, char *argv[])
{

    int       val;

    if (argc != 2)
        err_quit("usage: a.out <descriptor#>");

    if ((val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0)
        err_sys("fcntl error for fd %d", atoi(argv[1]));

    switch (val & O_ACCMODE) {
    case O_RDONLY:
        printf("read only");
        break;

    case O_WRONLY:
        printf("write only");
        break;

    case O_RDWR:
        printf("read write");
        break;

    default:
        err_dump("unknown access mode");
    }

    if (val & O_APPEND)
        printf(", append");
    if (val & O_NONBLOCK)
        printf(", nonblocking");
#if defined(O_SYNC)
    if (val & O_SYNC)
        printf(", synchronous writes");
#endif
#if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC)
    if (val & O_FSYNC)
        printf(", synchronous writes");
#endif
    putchar('\n');
    exit(0);
}
这是程序的代码。
回复 支持 反对

使用道具 举报

发表于 2009-5-28 22:38:45 | 显示全部楼层
Post by amazingjxq;1990999
这是《Unix 环境高级编程》中的一个例子的运行结果。
有这本书的可以看3.14节。
a.out接受一个参数,该参数是一个文件描述符,打印该描述符的文件标志说明。
如是只读还是读写等等。
疑惑的是为何能这样运行?
    $ ./a.out 0 < /dev/tty
    read only
    $ ./a.out 1 > temp.foo
    $ cat temp.foo
    write only
    $ ./a.out 2 2>>temp.foo
    write only, append
    $ ./a.out 5 5 <>temp.foo
    read write
希望能解释一下上面四个是怎么运行的.


个人一些理解:
在Linux下,0表示默认的输入;1表示默认的输出;2表示错误
默认输入 只可读
默认输出 只可写
默认出错 只可写;但是不知道为什么少了write only
而其他的描述符,若咩有重定向的话,应该都是可读可写的
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表