I'm writing a little application under Linux (embedded on ARM) that is running two threads. I do a "popen" in a function and this creates a deadlock for the second thread that enters the function. However, the first thread that entered the function first still runs correctly.
Here is some code sample:
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int sendCommand(
const std:开发者_开发百科:string& command, std::string& answer)
{
FILE* fd; // File descriptor to command output
char answer_c[COMMAND_BUFFER_SIZE]; // The answer as char[]
int answerLength = 0; // The length of the answer
pthread_mutex_lock( &mutex1 );
// A probe
cout << "VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV" << endl;
fd = popen(command.c_str(), "r"); // <- Second thread entering is stuck here ...
if(fd <= 0)
{
cout << "couldn't popoen !" << endl;
return -1;
}
// A probe, never showed by second thread entering the function
cout << "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZzz" << endl;
// ... Omitted code ...
// Close the file descriptor
pclose(fd);
pthread_mutex_unlock( &mutex1 );
}
I really have the felling that I'm missing something important. How could a deadlock happen with popen? Is the problem comming from the standard libc or Linux kernel ?
Any pointer is strongly appreciated !
Regards,
Since popen does a fork (which is not thread safe), then popen is not thread safe as well.
This question and answers might help you a bit.
精彩评论