When I try to open /proc/net/tcp from a child POSIX thread in C++ it fails with a "No such file or directory" error. If I try to open it from the parent thread it succeeds every time, and the process of opening/closing it in the parent thread then makes it succeed about a third of the time in the child thread too. I can open /proc/uptime in the child thread 100% of the time without issue. Here's some example code which can be compiled with "g++ -Wall test.cc -o test -pthread":
#include <iostream>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <pthread.h>
using namespace std;
void * open_test (void *)
{
ifstream in;
in.open("/proc/net/tcp");
if (in.fail())
cout << "Failed - " << strerror(errno) << endl;
else
cout << "Succeeded" << endl;
in.close();
return 0;
}
int main (int argc, char * argv[])
{
open_test(NULL);
pthread_t thread;
pthread_create(&thread, NULL, open_test, NULL);
pthread_exit(0);
}
I am running this on an Ubuntu 12.04 box with an Intel i5-2520M (2 cores * 2 virtual cores) on Linux kernel 3.2.0. Here is the output of me running the above code 6 times in a row:
mike@ung:/tmp$ ./test
Succeeded
Failed - No such file or directory
mike@ung:/tmp$ ./test
Succeeded
Succeeded
mike@ung:/tmp$ ./test
Succeeded
Failed - No such file or directory
mike@ung:/tmp$ ./test
Succeeded
Failed - No such file or directory
mike@ung:/tmp$ ./test
Succeeded
Succeeded
mike@ung:/tmp$ ./test
Succeeded
Failed - No such file or directory
mike@ung:/tmp$
It's probably worth noting that I don't have this problem if I use fork instead of posix threads. If I use fork, then the child process has no problems reading /proc/net/tcp
Just a couple of data points to throw in.... It looks like this is a regression in Linux as 2.6.35 seems to work 100% of the time. 3.2.0 pukes most of the time even on my slow old Pentium M based laptop.