yukang1744 发表于 2020-3-18 09:02:39

【求助】linux select阻塞

如题,我在线程中使用FD_SET了,程序还是卡在select这里。请教各位大神!代码如下。


#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>   // mkfifo
#include <sys/stat.h>   // mkfifo
#include <pthread.h>


#define MAX_BUFFER_SIZE 1024 /* 缓冲区大小*/
#define IN_FILES 2 /* 多路复用输入文件数目*/
#define MAX(a, b) ((a > b)?(a)b))

int fds = {1,2};
fd_set inset;

void *testfunc(void *arg)
{
    inti;
    sleep(1);
    for (i = 0; i < IN_FILES; i++)
    {
      FD_SET(fds, &inset);
    }
}
int main(void)
{
    char buf;
    int i, res, maxfd;
    pthread_t _mthread;
    struct timeval tv;

   FD_ZERO(&inset);
   if (pthread_create(&_mthread, NULL, (void *)testfunc, NULL) != 0)
   {
         fprintf(stderr, "thread create failed\n");
         return -1;
   }   

    /*取出两个文件描述符中的较大者*/
    maxfd = MAX(fds, fds);
    res = select(maxfd + 1, &inset, NULL, NULL, NULL);
    for (i = 0; i < IN_FILES; i++)
   {
            if(FD_ISSET(fds, &inset))
                  printf("Select ok\n");
    }
    return 0;
}

knight_sh 发表于 2020-3-18 09:51:39

楼主不妨说说你需要实现什么功能,另外你看select的man手册了么,select是会阻塞的,直到你的集合某个文件可读、写、执行才返回(或者被信号中断,如果设置超时,时间到也会返回),再说开个线程就为了FD_SET?

lkm_unication 发表于 2020-3-18 11:25:09

你理解错FD_SET和select了,select是由kernel唤醒的,不是由另一个进(线)程通过FD_SET唤醒的。建议参考一下网上关于select的测试用例。

dbwu8280 发表于 2020-3-18 22:20:56

不会,帮顶,赚分走人。

visa198 发表于 2020-3-18 22:25:28

google 百度 bing

canspider 发表于 2020-3-19 07:31:27

这代码鬼斧神工
随便搜一个select的demo,也不会写出这样的代码
select的流程是先用FD_ZERO清空fds,然后把要监听的fd通过FD_SET写到fds中,然后select监听fds
有事件发生时,通过FD_ISSET判断是哪个fd产生的
fd是系统资源,由系统api创建,设置,销毁,不是随便写个1,2,3就能操作了
页: [1]
查看完整版本: 【求助】linux select阻塞