Chinaunix首页 | 论坛 | 博客
  • 博客访问: 428151
  • 博文数量: 132
  • 博客积分: 2511
  • 博客等级: 大尉
  • 技术积分: 1385
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-11 15:10
文章分类

全部博文(132)

文章存档

2012年(18)

2011年(35)

2010年(60)

2009年(19)

分类: LINUX

2011-05-22 10:12:36

  1. /* Exercise3.5:tell the difference between "./a.out > outfile 2>&1" and "./a.out 2>&1 > outfile"
  2.  *
  3.  * 输出:
  4.  * [root@localhost file]# ./uidgid
  5.  * uid = 0, gid = 0
  6.  * haha: No such file or directory
  7.  *
  8.  * [root@localhost file]# ./uidgid > /tmp/ee 2>&1
  9.  * [root@localhost file]# cat /tmp/ee
  10.  * haha: No such file or directory
  11.  * uid = 0, gid = 0
  12.  *
  13.  * [root@localhost file]# ./uidgid 2>&1 > /tmp/ff
  14.  * haha: No such file or directory
  15.  * [root@localhost file]# cat /tmp/ff
  16.  * uid = 0, gid = 0
  17.  *
  18.  * shell从左向右处理命令行,所以二者区别如下:
  19.  * ./a.out > outfile 2>&1 ,先把stdout重定向到outfile,再把stderr重定向到stderr,此时stdout和stderr都指向同一个文件表项;
  20.  * 相当于
  21.  * fcntl(1, F_DUPFD, fd_to_outfile);
  22.  * fcntl(2, F_DUPFD, 1);
  23.  * 不过奇怪的是,在程序的结果中,/tmp/ee里面为啥是stderr的在stdout前面?此时stdout是全缓冲的,因此printf执行后,内容还在
  24.  * 缓冲区里,难道和perror实现有关?
  25.  * 将perror改为printf后,则是haha在前。
  26.  *
  27.  * ./a.out 2>&1 > outfile ,先将stderr重定向到stdout,然后再把stdout重定向到outfile,所以此时stderr指向stdout本来指向
  28.  * 的文件表项,而stdout则指向了新的文件表项,所以stdout的内容会输出到文件中,而stderr的内容输出到终端。相当于
  29.  * fcntl(2, F_DUPFD, 1);
  30.  * fcntl(1, F_DUPFD, fd_to_outfile);
  31.  */

  32. #include "apue.h"
  33. #include <sys/types.h>
  34. #include <sys/stat.h>
  35. #include <fcntl.h>

  36. int
  37. main(void)
  38. {
  39.     printf("uid = %d, gid = %d\n", getuid(), getgid());

  40.     if(open("./haha", O_RDONLY))
  41.     {
  42.         perror("haha");
  43.         exit(-1);
  44.     }

  45.     exit(0);
  46. }
阅读(534) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~