[英]select () C lib function always returns 0
我目前正在嘗試使用命名管道作為IPC來同時運行服務器以同時處理多個“客戶端”(本地進程)請求。 客戶端可以在上面寫,但是服務器上的select()函數似乎無法正常工作,它始終返回0。
這是服務器的主要代碼:
int main (int argc, char const *argv[]){
fd_set set; //fds to monitor
Request * r;
struct timeval tv; //timeout
Connection *c; //where the fd will be saved
fd_set foo; //debugging purpose
//opens the NamedPipe and saves de ReadOnly fd on c
if( (c = openConnection()) == NULL) {
return ERROR_OPEN_REQUEST_QUEUE;
}
//sets up the fds to monitor FD_ZERO and FD_SET
setConnection(c, &set);
FD_ZERO(&foo);
tv.tv_sec = 2;
tv.tv_usec = 0;
while(1){
int fdCount = select(2, &set, &foo, &foo, &tv);
//it seems select directly modifies this value
tv.tv_sec = 2;
//saw it on another post
setConnection(c, &set);
if( fdCount > 0){
r = getRequest(c);
if( r != NULL ){
TODO processRequest(r);
}
} else {
printf("No requests to process\n");
}
}
return 0;
}
服務器和客戶端都使用openConnection從NamedPipe獲取fd。 openConnections調用此函數並創建一個連接對象:
int * openNamedPipe(char * name) {
char origin[] = "/tmp/";
char myfifo[80];
int * fd;
fd = malloc(sizeof(int)*2);
strcpy(myfifo,origin);
strcat(myfifo,name);
mkfifo(myfifo, 0777);
fd[0] = open(myfifo, O_RDONLY|O_NONBLOCK);
fcntl(fd[0], F_SETFL, fcntl(fd[0], F_GETFL) &~O_NONBLOCK);
fd[1] = open(myfifo, O_WRONLY);
return fd;
}
我的問題如下:
我正在用cat手動檢查fifo,我能夠從shell中讀取內容。 因此,如果客戶端能夠寫入,則服務器應該能夠使用ReadOnly fd進行讀取。
添加setConnection函數以防萬一:
void setConnection(Connection * connection, fd_set* set){
FD_ZERO(set);
FD_SET(connection -> np -> fd, set);
return;
}
select
第一個參數應該是編號最高的文件描述符+1。 您正在傳遞值2,因此您的選擇僅關注fds 0和1(如果它們在傳遞的集中設置)。 你的管道真的使用那些嗎? 如果不是,則需要測試最高的代碼,然后將其傳遞給選擇。
另一件事,如果您不想觀看這些事件,似乎應該只傳遞NULL而不是foo
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.