[英]Different socket descriptor in main and thread function
My main function code is shown below 我的主要功能代码如下所示
if (argc < 2 || argc > 4)
{
printf("usage: server <port> [<ip>]\n");
exit(1);
}
TCPStream* stream = NULL;
TCPAcceptor* acceptor = NULL;
if (argc == 3)
{
acceptor = new TCPAcceptor(atoi(argv[1]), argv[2]);
}
else
{
acceptor = new TCPAcceptor(atoi(argv[1]));
}
if (acceptor->start() == 0)
{
while (1)
{
stream = acceptor->accept();
if (stream != NULL)
{
/*
ssize_t len;
char line[256];
while ((len = stream->receive(line, sizeof(line))) > 0) {
line[len] = 0;
printf("received - %s\n", line);
stream->send(line, len);
*/
cout << "in main" << stream->getsockdescriptor() << endl;
pthread_t sniffer_thread;
if( pthread_create( &sniffer_thread, NULL, connection_handler, (void*)&stream) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
pthread_join( sniffer_thread , NULL);
}
delete stream;
}
}
exit(0);
}
and thread function code is shown below 线程功能代码如下所示
void *connection_handler(void * args)
{
TCPStream *stream = (TCPStream *)args;
ssize_t len;
char line[256];
cout << "check1" << endl;
cout << stream->getsockdescriptor() << endl;
while ((len = stream->receive(line, sizeof(line))) > 0)
{
cout << "check2" << endl;
line[len] = 0;
printf("received - %s\n", line);
stream->send(line, len);
}
}
Even though I passed object to thread function. 即使我将对象传递给线程函数。 I am getting different file descriptor value.
我得到了不同的文件描述符值。 In main it is showing correct.Start(),Accept(),receive() are wrapper function
主要显示正确。Start(),Accept(),receive()是包装函数
The problem is the pthread_create
call and the arguments you pass there: 问题是
pthread_create
调用和您在此处传递的参数:
pthread_create( &sniffer_thread, NULL, connection_handler, (void*)&stream)
Here you don't pass a pointer to a TCPStream
object (ie TCPStream*
), but a pointer to a pointer to a TCPStream
object (ie TCPSTream**
). 在这里,你不传递一个指向
TCPStream
对象(即TCPStream*
),而是一个指向指针TCPStream
对象(即TCPSTream**
)。
This will lead to undefined behavior in your thread function because you treat the pointer as a pointer to TCPStream
. 这将导致线程函数发生不确定的行为 ,因为您将指针视为指向
TCPStream
的指针。
Simply drop the address-of operator &
when calling pthread_create
and it should start working. 只需在调用
pthread_create
时删除地址运算符&
,它应该开始工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.