C中TCP服务器中的线程处理
Thread handling in TCP server in C
这是我第一次post来这里,所以我想和大家打个招呼。
我在编写 TCP 时遇到了一些问题,我想要一个单独的线程,允许用户键入退出指令来终止进程。问题是好像不是运行。程序在接受时暂停,我无法将任何内容传递给线程函数。
线程函数:
void *loop_stop()
{
while(progr_control != 'q')
progr_control = getchar();
return NULL;
}
主要的(我省略了一些我认为不会引起问题的代码):
pthread_t thread_id;
pthread_create(&thread_id, NULL, loop_stop, NULL);
do
{
listen(sock_fd, 5);
int addr_len = sizeof(client_addr);
if( (new_sock_fd = accept(sock_fd, (struct sockaddr *) &client_addr, &addr_len)) < 0)
{
perror("Problems with incoming connection");
return -1;
}
else
//here is the ommited part-as I've said this loop stops at accept
}while(progr_control != 'q');
如果有人能找到错误,或提出其他处理任务的方法,我将不胜感激
正如布莱恩所说:
'accept' 将使线程等待传入的连接,因此 "quit check" 是不可能的。另一种方法是使用 ctrl+c 退出。
这是我第一次post来这里,所以我想和大家打个招呼。 我在编写 TCP 时遇到了一些问题,我想要一个单独的线程,允许用户键入退出指令来终止进程。问题是好像不是运行。程序在接受时暂停,我无法将任何内容传递给线程函数。
线程函数:
void *loop_stop()
{
while(progr_control != 'q')
progr_control = getchar();
return NULL;
}
主要的(我省略了一些我认为不会引起问题的代码):
pthread_t thread_id;
pthread_create(&thread_id, NULL, loop_stop, NULL);
do
{
listen(sock_fd, 5);
int addr_len = sizeof(client_addr);
if( (new_sock_fd = accept(sock_fd, (struct sockaddr *) &client_addr, &addr_len)) < 0)
{
perror("Problems with incoming connection");
return -1;
}
else
//here is the ommited part-as I've said this loop stops at accept
}while(progr_control != 'q');
如果有人能找到错误,或提出其他处理任务的方法,我将不胜感激
正如布莱恩所说: 'accept' 将使线程等待传入的连接,因此 "quit check" 是不可能的。另一种方法是使用 ctrl+c 退出。