tags:

views:

138

answers:

2

I have the following code which ends up forever reading '/proc/cpuinfo' as it keeps getting the same result every read. Why doesn't the file pointer get advanced and reach eof ever? Seems this special file has different semantics.

  const int bufSize = 4096;
  char buf[bufSize + 1];
  const string cpuInfo = "/proc/cpuinfo";
  int cpuFD = ::open(cpuInfo.c_str(), O_RDONLY);

  if (cpuFD == -1) {
    logOutputStream << "Failed attempt to open '" << cpuInfo << "': "
                    << strerror(errno) << endl;
  } else {
    assert(bufSize <= SSIZE_MAX);

    logOutputStream << "Contents of: '" << cpuInfo << "'.\n";

    for (int nRead = ::read(cpuFD, buf, bufSize); nRead != 0;) {
      if (nRead == -1) {
        logOutputStream << "Failed attempt to read '" << cpuInfo << "': "
                        << strerror(errno) << endl;
        break;
      } else {
        buf[nRead] = '\0';
        logOutputStream << buf;
      }
    }
    if (::close(cpuFD) == -1) {
      logOutputStream << "Failed attempt to close '" << cpuInfo << "': "
                      << strerror(errno) << endl;
    }
  }
A: 

What happens if you try dumping the content into an actual text file with something like

cat /proc/cpuinfo > cpuinfo.txt

and then reading that file ?

nairdaen
+4  A: 
for (int nRead = ::read(cpuFD, buf, bufSize); nRead != 0;) {

is wrong. You're using read as an initializer, so read is only being called once, not once per loop. After that, you're just looping forever printing it out (because nothing is changing nRead).

derobert
Thanks for detecting that brain fart!
WilliamKF