当我调用sem_post()
函数时,我遇到了分段错误的问题。这是我的代码(检查超时):
父线程:
void * Client::Init(void * args)
{
char * clientIP;
// clientIP = ... IP from other program part
int * timeoutSemaphoreValue;
sem_unlink(clientIP); // always new semaphore
sem_t * semaphore;
semaphore = sem_open(clientIP, O_CREAT | O_EXCL, O_RDWR, 0);
if(errno == EEXIST)
cout << "Problem z synchronizacją wątków (semafory) - nieobsłużone." << endl;
pthread_create(&clientStatesThread, NULL, VOID_T Client::ClientStatesLoop, clientIP);
while(status > 0)
{
sem_getvalue(semaphore, timeoutSemaphoreValue);
if(*(client->timeoutSemaphoreValue) == 1)
throw SocketException(0x01, "Timeout.", errno)
}
}
一个子线程方法:
void * Client::ClientStatesLoop(void * args)
{
char * clientIP = (char *)args;
sem_t * semaphore;
semaphore = sem_open(clientIP, O_CREAT, O_RDWR, 0);
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof (struct timeval));
...
while(1)
{
bufferInLen = recv(fd, bufferIn, BUF_SIZE, 0);
if((errno == EAGAIN) || (errno == EWOULDBLOCK))
{
sem_post(semaphore);
}
}
}
这是GDB日志:
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
TCP Server v.2.0
[New Thread 0x7ffff6fd6700 (LWP 2425)] // another thread
[New Thread 0x7ffff67d5700 (LWP 2426)] // another thread
Połączono.
[New Thread 0x7ffff5fd4700 (LWP 2529)] // parent thread
[New Thread 0x7ffff57d3700 (LWP 2530)] // child thread
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff57d3700 (LWP 2530)]
0x00007ffff7bcb1c0 in sem_post () from /lib/x86_64-linux-gnu/libpthread.so.0
当我致电sem_post()
时,这段错误的原因是什么?也许我应该使用除sem_open()
以外的其他方法在子线程中使用名称semafore打开?