C-Unix套接字 - 非阻塞读 [英] C- Unix Sockets - Non-blocking read

查看:164
本文介绍了C-Unix套接字 - 非阻塞读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个简单的客户端 - 服务器的聊天程序。在客户端,我分拆另一个线程来从服务器读取任何数据进来的。问题是,我想正常终止的第二个线程,当一个人从主线程注销。我试图用一个共享变量运行终止,问题是,插座阅读()命令是阻塞命令,因此,如果我这样做,而(运行== 1),服务器读取返回之前送东西和而条件可以再次检查。我要寻找一个方法(只有普​​通Unix套接字)做非阻塞读,基本上都是某种形式的PEEK(的)会的工作,因为我可以不断地检查循环,看看我完成了。

读线程循环低于,现在它没有任何互斥对共享变量,但我计划增加以后不用担心! ;)

 无效* serverlisten(无效* vargp)
{
    而(运行== 1)
    {
        阅读(插座,readbuffer,sizeof的(readbuffer));
        的printf(客户端收到%S \\ n,readbuffer);
    }
    了pthread_exit(NULL);
}


解决方案

您可以不插座地锁定在另一篇文章中建议加用select等待输入,超时,像这样的:

  FD_SET输入;
FD_ZERO(安培;输入);
FD_SET(SD,&安培;输入);
timeval结构超时;
timeout.tv_sec =秒;
timeout.tv_usec =毫秒* 1000;
INT N =选择(SD + 1,&安培;输入,NULL,NULL,&安培;超时);
如果(N == -1){
    //有问题
}否则如果(N == 0)
    继续; //超时
如果(FD_ISSET(SD,&安培;!输入))
   ; //再次不对劲
//这里我们可以呼之不应可阻止读

I am trying to make a simple client-server chat program. On the client side I spin off another thread to read any incomming data from the server. The problem is, I want to gracefully terminate that second thread when a person logs out from the main thread. I was trying to use a shared variable 'running' to terminate, problem is, the socket read() command is a blocking command, so if I do while(running == 1), the server has to send something before the read returns and the while condition can be checked again. I am looking for a method (with common unix sockets only) to do a non-blocking read, basically some form of peek() would work, for I can continually check the loop to see if I'm done.

The reading thread loop is below, right now it does not have any mutex's for the shared variables, but I plan to add that later don't worry! ;)

void *serverlisten(void *vargp)
{
    while(running == 1)
    {
        read(socket, readbuffer, sizeof(readbuffer));
        printf("CLIENT RECIEVED: %s\n", readbuffer);
    }
    pthread_exit(NULL);
}

解决方案

You can make socket not blockable, as suggested in another post plus use select to wait input with timeout, like this:

fd_set         input;
FD_ZERO(&input);
FD_SET(sd, &input);
struct timeval timeout;
timeout.tv_sec  = sec;
timeout.tv_usec = msec * 1000;
int n = select(sd + 1, &input, NULL, NULL, &timeout);
if (n == -1) {
    //something wrong
} else if (n == 0)
    continue;//timeout
if (!FD_ISSET(sd, &input))
   ;//again something wrong
//here we can call not blockable read

这篇关于C-Unix套接字 - 非阻塞读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆