整体情况是这样的:开启一个线程持续向一个文件中写入数据,而主线程则使用select监听文件描述符是否可读,
写入操作都是成功的,但是select的结果却一直是超时。难道是普通文件不能select?但是man手册并未看到明确说明。 PO下代码:
#include <stdio.h> #include <sys/select.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <errno.h> #include <pthread.h> #include <string.h> #include <sys/socket.h> #define LOCAL_CONST_IOBUF_LEN (64) #define LOCAL_CONST_LOOP_AMOUNT (500) void* write_thread(void* pv) { const pthread_t tid = pthread_self(); if (NULL == pv) { printf("thread:%u report: arg is null, exit.\n", tid); return pv; } int fd = *((int*)pv); size_t nWrote; char szWRBuf[LOCAL_CONST_IOBUF_LEN]; sprintf(szWRBuf, "writer thread %u.\n", tid); size_t nLoopCtr = 0; while (nLoopCtr++ < LOCAL_CONST_LOOP_AMOUNT) { nWrote = write(fd, szWRBuf, strlen(szWRBuf)); printf("write to fd(%d) %u bytes.\n", fd, nWrote); sleep(2); } printf("thread %u exit.\n", tid); return pv; } int main(int argc, char** argv) { const char* fpath = "/tmp/cond"; const int fd = open(fpath, O_TRUNC | O_RDWR); if (fd <= 0) { printf("open %s failed.\n", fpath); return -1; } printf("test beg, fd(%d).\n", fd); pthread_t nWriteTid = 0; if (0 == pthread_create(&nWriteTid, NULL, write_thread, (void*)&fd)) { size_t nLoopCtr = 0; while (nLoopCtr++ < LOCAL_CONST_LOOP_AMOUNT) { fd_set rdfs; FD_ZERO(&rdfs); FD_SET(fd, &rdfs); struct timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; const int nSelect = select(2, &rdfs, NULL, NULL, &tv); if (nSelect < 0) { printf("select:error,ret %d, errno %d.\n", nSelect, errno); break; } else if (0 == nSelect) { printf("select:no data for reading.\n"); continue; } char szRDBuf[LOCAL_CONST_IOBUF_LEN]; memset(szRDBuf, '\0', sizeof(szRDBuf)); const size_t nRead = read(fd, szRDBuf, sizeof(szRDBuf)-1); if (-1 == nRead) { printf("select:read failed(-1).errno %d", errno); break; } else if (0 == nRead) { printf("select:read nothing, EOF reached.errno %d.\n", errno); continue; } szRDBuf[sizeof(szRDBuf)-1] = '\0'; printf("select:szRDBuf:%s\n", szRDBuf); } pthread_cancel(nWriteTid); void* pvRet = NULL; pthread_join(nWriteTid, &pvRet); } close(fd); printf("main exit.\n"); return 0; }