这个问题在某种程度上类似于坏文件描述符,但它根本不一样。我知道这是“糟糕的问题”(也许是“过于本地化”),但我无法弄清楚,我现在没有任何想法。
介绍
我有一个管理器线程,它启动了 75 个其他线程。这些线程中的每一个都做了很多事情,所以我将只描述相关的。
请注意:如果我只启动几个线程 - 例如 3 或 5 或 10,则不会出现此错误!这让我觉得,这是一些多线程问题,但似乎并非如此。您将在下一节中看到原因。
因此,在以下 2 种情况下,有时我会收到此错误Bad file descriptor
:
情况1
错误出现在TinyXML
有一个 xml 文件,所有线程都需要它。所有这些线程都TinyXML
用于解析文件。所有这些线程都以只读方式使用此文件!(我知道这可以优化,但无论如何)。
所以,导致Bad file descriptor
错误的代码是这样的:
// ...
// NOTE: this is LOCAL, other threads do NOT have access to it
TiXmlDocument doc;
doc.LoadFile( filename );
// and here's the LoadFile:
bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding )
{
//...
FILE* file = fopen( value.c_str (), "rb" );
if ( file )
{
// this IS executed, so file is NOT NULL for sure
bool result = LoadFile( file, encoding );
//...
}
//...
}
bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding )
{
// ...
long length = 0;
fseek( file, 0, SEEK_END );
// from the code above, we are SURE that file is NOT NULL, it's valid, but
length = ftell( file ); // RETURNS -1 with errno: 9 (BAD FILE DESCRIPTOR)
// how is this possible, as "file" is not NULL and it appears to be valid?
// ...
}
案例2
这有点复杂。我已经删除了对返回值的检查,但我在我的真实代码中有它们,所以这不是问题
int hFileR = open( sAlarmFileName.c_str(), O_CREAT | O_RDONLY,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH );
// hFileR is > 0 for sure, so success
flock( hFileR, LOCK_EX ) /* the result is > 0 for sure, so success*/
// read the file into a string
while( (nRes = read(hFileR, BUFF, MAX_RW_BUFF_SIZE)) > 0 ) // ...
//Write new data to file: reopen/create file - write and truncate mode
int hFileW = open( sAlarmFileName.c_str(),
O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR |
S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH );
// hFileW is > 0 for sure, so success
do
{
int nWrtRes = write( hFileW,
szText + nBytesWritten, nSize - nBytesWritten );
// nWrtRes is always >= 0, so success
nBytesWritten += nWrtRes;
}
while( nSize > nBytesWritten );
close( hFileW ); // this one is successful too
if( flock(hFileR, LOCK_UN) == -1 )
{
// THIS FAILS and executes _Exit( FAILURE );
}
if( close( hFileR ) < 0 )
{
// if the previous one do not fail, this one is successful too
}
对不起,很长的问题。有任何想法吗?