简体   繁体   English

如何防止stdin流在程序启动时从关联的文件描述符中读取数据?

[英]How to prevent stdin stream from reading data from associated file descriptor on program start?

I'm using select() call to detect input presence in the main cycle of my program. 我正在使用select()调用来检测程序主循环中的输入是否存在。 This makes me use raw file descriptor (0) instead of stdin. 这使我使用原始文件描述符(0)代替了stdin。

While working in this mode I've noticed that my software occasionally loses a chunk of input at the beginning. 在这种模式下工作时,我注意到我的软件一开始偶尔会丢失大量输入。 I suspect that stdin consumes some of it on the program start. 我怀疑stdin在程序启动时会消耗掉其中的一些。 Is there a way to prevent this behavior of stdin or otherwise get the whole input data? 有没有办法防止这种stdin的行为或获取整个输入数据?

The effect described can be reproduced only with some data on standard input at the very moment of program start. 在程序启动的那一刻,所描述的效果只能通过标准输入上的一些数据来再现。 My executable should be used as xinetd service in a way that it always has some input on the start. 我的可执行文件应作为xinetd服务使用,以使其始终在开始时就具有一些输入。

Standard input is read in the following way: 通过以下方式读取标准输入:

Error processInput() {
  struct timeval ktimeout;
  int fd=fileno(stdin);
  int maxFd=fd+1;
  FD_ZERO(&fdset);
  FD_SET(fd, &fdset);
  ktimeout.tv_sec = 0;
  ktimeout.tv_usec = 1;
  int selectRv=-1;
  while ((selectRv=select(maxFd, &fdset, NULL, NULL, &ktimeout)) > 0) {
    int left=MAX_BUFFER_SIZE-position-1;
    assert(left>0);
    int bytesCount=read(fd, buffer+position, left);
    //Input processing goes here
  }
}

Don't mix cooked and raw meat together. 不要将熟肉和生肉混合在一起。 Try replacing the read() call with the equivalent fread() call. 尝试用等效的fread()调用替换read()调用。

It is very likely that fileno(stdin) is initializing the stdin object, causing it to read and buffer some input. fileno(stdin)很可能正在初始化stdin对象,从而使其读取并缓冲某些输入。 Or perhaps you are already calling something that causes it to initialize (scanf(), getchar(), etc...). 也许您已经在调用某种导致其初始化的内容(scanf(),getchar()等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM