b.buchhold
b.buchhold

Reputation: 3896

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.

However, I if called like that (using bash):

./myProg <(head -n 100 xxx)

Area 1 will be entered 100 times and Area 2 will be entered 0 times. Both assertions (in.good()) do pass. 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.

I wonder what the reason behind that is.

Upvotes: 1

Views: 83

Answers (1)

ccarton
ccarton

Reputation: 3666

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. 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.

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. You wouldn't expect to be able to read the data twice via cin in that scenario. This is the same.

Upvotes: 2

Related Questions