select的测试demo

#include <sys/select.h>
int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
void FD_CLR(int fd, fd_set *set);
int  FD_ISSET(int fd, fd_set *set);//判断描述符是否加到描述符集中
void FD_SET(int fd, fd_set *set);
void FD_ZERO(fd_set *set);
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>
#include<pthread.h>
#include <string.h>

#define FILE_NAME  ("./test.txt")
#define MAX(a,b) ((a>b)?a:b)
static int s_f_fd = -1;
char *buf = "hello johan";
char buf_1[32] = {0};
static pthread_t t1 = -1;
static pthread_t t2;

int open_file(char* file_name)
{
    int fd = open(file_name,O_CREAT|O_APPEND|O_RDWR);
    if(-1 == fd)
        goto err;
    else    
        return fd;

    err:
        printf("open file error\n");
        return -1;
}

int test_write_fd(int fd)
{
    int ret = write(s_f_fd,buf,strlen(buf));
    if(-1 == ret)
        goto err;

    return 0;
    err:
        printf("write file error\n");
        return -1;
}
void* func_1(void* arg)
{
    // int a = 10;
    for(int a = 5;a > 0;a--)
    {
        sleep(1);
        
    }
    printf("sleep end\n");
    printf("s_f_fd = %d\n",s_f_fd);
    if(-1 == test_write_fd(s_f_fd))
    {
        pthread_exit(NULL);
    }
    pthread_exit(NULL);//线程正常退出
}


void* func_2(void* arg)
{
    fd_set rfds;
    struct timeval tv;
    int retval;

    /* Watch stdin (fd 0) to see when it has input. */

    FD_ZERO(&rfds);
    FD_SET(0, &rfds);

    s_f_fd = open_file(FILE_NAME);
    if(-1 == s_f_fd)
    {
        pthread_exit(NULL);
    }
    else
        FD_SET(s_f_fd, &rfds);

    /* Wait up to five seconds. */

    tv.tv_sec = 5;
    tv.tv_usec = 0;

    retval = select(MAX(0,s_f_fd) + 1, &rfds, NULL, NULL, &tv);
    /* Don't rely on the value of tv now! */

    if (retval == -1)
        perror("select()");
    else if (retval)
    {
        printf("Data is available now.\n");
        /* FD_ISSET(0, &rfds) will be true. */
        // if (FD_ISSET(s_f_fd, rfds))
        if(FD_ISSET(s_f_fd, &rfds))
        {
            if(-1 == test_write_fd(s_f_fd))
            {
                pthread_exit(NULL);
            }
        }
    }
    else
        printf("No data within five seconds.\n");
    
    pthread_exit(NULL);//线程正常退出
}

int main(void)
{
    int *pret = NULL;
    int ret = pthread_create(&t2,NULL,func_2,NULL);
    if(ret)
        return -1;

    pthread_join(t2,(void**)&pret);
    exit(EXIT_SUCCESS);
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秃秃秃秃哇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值