Linux C,为什么fcntl作用于STDIN也会影响STDOUT和STDERR? [英] Linux C, Why fcntl act on STDIN will also affect on STDOUT and STDERR?

查看:89
本文介绍了Linux C,为什么fcntl作用于STDIN也会影响STDOUT和STDERR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在stdin上执行功能fcntl时遇到问题,当我将stdin FD状态标志设置为O_NONBLOCK时,它工作良好,但有副作用. stdout和stderr的状态标志也已更改为O_NONBLOCK.

I have met a problem when acting function fcntl on stdin, when I set the stdin FD status flag to O_NONBLOCK, It works well but within a side effect. The status flag of stdout and stderr has also changed to O_NONBLOCK.

我研究了功能fcntlSYSCALL_DEFINE3do_fcntl的源代码,但没有任何帮助.还有stackoverflow或google.我认为这可能与内核或glibc实现有关.

I investigated the source code of function fcntl, SYSCALL_DEFINE3 and do_fcntl, but got nothing helps. Also stackoverflow or google. I consider that it may related to kernel or glibc implementation.

我的计算机是x86_64上的Ubuntu 12.04,已安装gcc 4.6.3.

My computer is Ubuntu 12.04 on x86_64, within gcc 4.6.3 installed.

  int flag = 0;
  int value = O_NONBLOCK;
  int fd = open("./tmp", O_RDONLY);

  if(-1 == (flag = fcntl(fd, F_GETFL)))
      fprintf(stdout, "%d:%s\n", errno, strerror(errno));

  flag = fcntl(stdin->_fileno, F_GETFL);
  flag = fcntl(stderr->_fileno, F_GETFL);
  if(-1 == (flag = fcntl(stdout->_fileno, F_GETFL)))
      fprintf(stdout, "%d:%s\n", errno, strerror(errno));

  flag = fcntl(stdout->_fileno, F_SETFL, flag | O_NONBLOCK);

  flag = fcntl(fd, F_GETFL);
  flag = fcntl(stdin->_fileno, F_GETFL);
  flag = fcntl(stdout->_fileno, F_GETFL);
  flag = fcntl(stderr->_fileno, F_GETFL);

  flag = fcntl(stdin->_fileno, F_SETFL, flag | O_APPEND);

  flag = fcntl(fd, F_GETFL);
  flag = fcntl(stdin->_fileno, F_GETFL);
  flag = fcntl(stdout->_fileno, F_GETFL);
  flag = fcntl(stderr->_fileno, F_GETFL);

  close(fd);

这是我针对此问题的代码.

This is my code for this problem.

推荐答案

登录过程(或终端打开过程)传统上使用的技巧"之一是以读写模式打开文件描述符0的终端(标准输入),然后复制文件描述符1和2(标准输出和标准错误).这意味着:

One of the 'tricks' traditionally used by the login process (or terminal opening process) is to open the terminal in read-write mode for file descriptor 0 (standard input), and then duplicate that for file descriptors 1 and 2 (standard output and standard error). This means that:

  1. 所有三个标准文件描述符共享相同的打开文件描述.
  2. 您可以写入标准输入,也可以读取标准输出或标准错误.
  3. 更改一个文件的描述信息会更改其他文件的信息.

fcntl()的F_GETFL和F_SETFL选项与打开的文件描述有关. fcntl()的F_GETFD和F_SETFD选项与文件描述符有关.

The F_GETFL and F_SETFL options to fcntl() are related to the open file description. The F_GETFD and F_SETFD options to fcntl() are related to the file descriptor.

给定的打开文件描述可能具有多个文件描述符,这些文件描述符在单个进程内(在dup()dup2()之后)或跨进程(由于fork()).

A given open file description may have several file descriptors associated with, either within a single process (after dup() or dup2()) or across processes (because of fork()).

这篇关于Linux C,为什么fcntl作用于STDIN也会影响STDOUT和STDERR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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