简体   繁体   English

IO关于文件描述符

[英]IO on file descriptors

I just ran into the following behavior and would like to know the reasons behind it: 我只是遇到以下行为,并想知道其背后的原因:

Assume a simplified program like that 假设像这样的简化程序

...
{
  std::ifstream in(argv[1]);
  assert(in.good());
  while (std::getline(in, line)) {
   // Area 1
  }
  in.close();
}
{
  std::ifstream in(argv[1]);
  assert(in.good());
  while (std::getline(in, line)) {
   // Area 2
  }
  in.close();
}

if such a program is call like that: 如果这样的程序被调用为:

./myProg xxx

Both , Area 1 and Area 2 will be entered n times where n is the number of lines in xxx. ,区域1和区域2将被输入n次,其中n是在XXX行数。

However, I if called like that (using bash): 但是,如果这样调用我(使用bash):

./myProg <(head -n 100 xxx)

Area 1 will be entered 100 times and Area 2 will be entered 0 times. 区域1将被输入100次, 区域2将被输入0次。 Both assertions (in.good()) do pass. 两个断言(in.good())都可以通过。 Appearently the second one passes a file descriptor (something like /dev/fd/63 if I print the argument) instead of an actual file and this thing can be opened for reading once - but when opened twice, it appears to be empty for the second call. 显然,第二个参数传递了文件描述符(如果我打印自变量,则类似于/ dev / fd / 63),而不是实际文件,并且该东西可以打开以读取一次-但是当打开两次时,对于第二次通话。

I wonder what the reason behind that is. 我不知道背后的原因是什么。

The head process is executed once by bash and has it's output redirected to a pipe which your process can access through that file inode. head进程由bash执行一次,并将其输出重定向到管道,您的进程可以通过该管道通过文件inode访问该管道。 Your program knows nothing about that head command and trying to close and re-open the file won't cause it to be executed again. 您的程序对该head命令一无所知,尝试关闭并重新打开该文件不会导致该文件再次执行。

It's similar to the situation you would have if your program read from cin and you execute it as head -n 100 xxx | ./myProg 这类似于您的程序从cin读取并以head -n 100 xxx | ./myProg执行的情况head -n 100 xxx | ./myProg head -n 100 xxx | ./myProg . head -n 100 xxx | ./myProg You wouldn't expect to be able to read the data twice via cin in that scenario. 在这种情况下,您将无法通过cin两次读取数据。 This is the same. 都一样

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

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