LinuxSir.cn,穿越时空的Linuxsir!

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

apue的fcntl里面有个demo,不过不是很懂,各位请指教一下

[复制链接]
发表于 2006-11-29 16:05:24 | 显示全部楼层 |阅读模式
demo是判断一个文件的file status,但是对里面的example data不是很明白,能告诉我原理吗?谢谢!
[PHP]$ ./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
[/PHP]
代码如下

  1. #include "apue.h"
  2. #include <fcntl.h>
  3. int
  4. main(int argc, char *argv[])
  5. {

  6.     int       val;

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

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

  11.     switch (val & O_ACCMODE) {
  12.     case O_RDONLY:
  13.         printf("read only");
  14.         break;

  15.     case O_WRONLY:
  16.         printf("write only");
  17.         break;

  18.     case O_RDWR:
  19.         printf("read write");
  20.         break;

  21.     default:
  22.         err_dump("unknown access mode");
  23.     }

  24.     if (val & O_APPEND)
  25.         printf(", append");
  26.     if (val & O_NONBLOCK)
  27.         printf(", nonblocking");
  28. #if defined(O_SYNC)
  29.     if (val & O_SYNC)
  30.         printf(", synchronous writes");
  31. #endif
  32. #if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC)
  33.     if (val & O_FSYNC)
  34.         printf(", synchronous writes");
  35. #endif
  36.     putchar('\n');
  37.     exit(0);
  38. }
复制代码

ps:我刚学linux,但是知道< >是重定向,但是对怎么会产生这个结果不是很明白.
发表于 2006-11-30 00:11:16 | 显示全部楼层
[PHP]$ ./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
[/PHP]
这个写成:
[PHP]$ ./a.out 0 0< /dev/tty
read only
$ ./a.out 1 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
[/PHP]
看得会更明白一些.
最后程序是测试第一个参数所指的文件描述符的状态.举个例子:
$ ./a.out 0 0< /dev/tty
这里,0</dev/tty 由SHELL处理,把描述符0 改为与/dev/tty相关,然后在程序里测试第一个参数,也就是0,如何测试的,APUE里讲得很明白了.
回复 支持 反对

使用道具 举报

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

本版积分规则

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