select的测试demo

#include 
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 
#include 
#include 
#include 
#include 
#include 

#include 
#include
#include 

#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);
}

在这里插入图片描述

你可能感兴趣的:(unix,c语言,linux)