#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>#defineFILE_NAME("./test.txt")#defineMAX(a,b)((a>b)?a:b)staticint s_f_fd =-1;char*buf ="hello johan";char buf_1[32]={0};staticpthread_t t1 =-1;staticpthread_t t2;intopen_file(char* file_name){int fd =open(file_name,O_CREAT|O_APPEND|O_RDWR);if(-1== fd)goto err;elsereturn fd;
err:printf("open file error\n");return-1;}inttest_write_fd(int fd){int ret =write(s_f_fd,buf,strlen(buf));if(-1== ret)goto err;return0;
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;structtimeval 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);}elseFD_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()");elseif(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);}}}elseprintf("No data within five seconds.\n");pthread_exit(NULL);//线程正常退出}intmain(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);}