关于linux socket和线程问题
当我在创建socket之前开启了一个线程,之后每当走到socket的accept函数是就会收到一个SIGSEGV信号。代码如下:
//创建线程的函数
typedef void*(*thread_function)(void *);
void beginthread(thread_function f, void *arg)
{
int res;
pthread_t a_thread;
pthread_attr_t thread_attr;
res = pthread_attr_init(&thread_attr);
if (0 != res) {
//perror("Create a thread failed");
exit(1);
}
res = pthread_attr_setdetachstate(&thread_attr,
PTHREAD_CREATE_DETACHED);
if (0 != res) {
//perror("Create a thread failed");
exit(1);
}
res = pthread_create(&a_thread,
&thread_attr,
f, arg);
if (0 != res) {
//perror("Create a thread failed");
exit(1);
}
(void)pthread_attr_destroy(&thread_attr);
}
//socket 部分代码
void sock_server::acceptsession()
{
beginthread(sock_server::checksession, NULL); //开启一个线程
int result;
sockaddr_in server_address;
serv_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(serv_port);
result = bind(serv_sockfd, (sockaddr *)&server_address, sizeof(server_address));
if (0 != result) {
printf("Accept session failed\n");
exit(1);
}
listen(serv_sockfd, 5);
while(serv_close) {
sockaddr_in client_address;
socklen_t client_address_length = sizeof(client_address);
int client_sockfd = accept(serv_sockfd,
(sockaddr *)&client_address,
&client_address_length); //收到一个SIGSEGV信号
.
.
.
.
如果把开线程的函数去掉就没有问题了, 我就想知道为什么会这样?