对于学校项目,我们将使用文件描述符和select()在一台机器上实现并发。在程序中,我们有RequestChannel对象,它们包含两个文件描述符,一个用于读取,一个用于写入,用于与执行开始时分离的单独进程进行通信。我可以用写文件描述符来解决问题,但读取fds似乎永远不会准备好。我可以帮助理解select()如何使用读写描述符吗?我看到的一切都是处理套接字,这只会让我感到困惑,我只是想了解一般文件描述符和select()。
这是我的选择循环:
fd_set readset, writeset;
FD_ZERO(&readset);
FD_SET(JohnDoe.read_fd(), &readset);
FD_SET(JoeSmith.read_fd(), &readset);
FD_SET(JaneSmith.read_fd(), &readset);
FD_ZERO(&writeset);
FD_SET(JohnDoe.write_fd(), &writeset);
FD_SET(JoeSmith.write_fd(), &writeset);
FD_SET(JaneSmith.write_fd(), &writeset);
int maxfd = 0;
maxfd = max(maxfd, JohnDoe.read_fd());
maxfd = max(maxfd, JohnDoe.write_fd());
maxfd = max(maxfd, JoeSmith.read_fd());
maxfd = max(maxfd, JoeSmith.write_fd());
maxfd = max(maxfd, JaneSmith.read_fd());
maxfd = max(maxfd, JaneSmith.write_fd());
int numready;
int count = 0;
while (count < 10) {
numready = select(maxfd + 1, &readset, &writeset, NULL, NULL);
if (numready == -1) {
cout << "Fatal error, aborting\n";
break;
}
else {
if(FD_ISSET(JohnDoe.write_fd(), &writeset)) { //write_fd() returns write file descriptor
JohnDoe.cwrite("data John Doe"); //one RequestChannel object
}
if(FD_ISSET(JoeSmith.write_fd(), &writeset)) {
JoeSmith.cwrite("data Joe Smith");
}
if(FD_ISSET(JaneSmith.write_fd(), &writeset)) {
JaneSmith.cwrite("data JaneSmith");
}
if(FD_ISSET(JohnDoe.read_fd(), &readset)) {
string s = JohnDoe.cread();
cout << "John Doe cread: " << s << "\n";
}
if(FD_ISSET(JoeSmith.read_fd(), &readset)) {
string s = JoeSmith.cread();
cout << "Joe Smith cread: " << s << "\n";
}
if(FD_ISSET(JaneSmith.read_fd(), &readset)) {
string s = JaneSmith.cread();
cout << "Jane Smith cread: " << s << "\n";
}
}
}
答案 0 :(得分:3)
在每次调用select()
之前,您需要重新初始化描述符集,因为select()
会修改描述符集。您可以在循环中使用FD_ZERO()
/ FD_SET()
或初始化&#39;原型&#39;将您复制的集合复制到传递给select()
的那些:
fd_set readset, writeset;
int maxfd = 0;
maxfd = max(maxfd, JohnDoe.read_fd());
maxfd = max(maxfd, JohnDoe.write_fd());
maxfd = max(maxfd, JoeSmith.read_fd());
maxfd = max(maxfd, JoeSmith.write_fd());
maxfd = max(maxfd, JaneSmith.read_fd());
maxfd = max(maxfd, JaneSmith.write_fd());
int numready;
int count = 0;
while (count < 10) {
FD_ZERO(&readset);
FD_SET(JohnDoe.read_fd(), &readset);
FD_SET(JoeSmith.read_fd(), &readset);
FD_SET(JaneSmith.read_fd(), &readset);
FD_ZERO(&writeset);
FD_SET(JohnDoe.write_fd(), &writeset);
FD_SET(JoeSmith.write_fd(), &writeset);
FD_SET(JaneSmith.write_fd(), &writeset);
numready = select(maxfd + 1, &readset, &writeset, NULL, NULL);
// etc...
}
答案 1 :(得分:2)
是的cjbrooks12是正确的。 select()系统调用之间需要reset the fd_set
。
它们充当输入/输出参数;它们由系统调用读取并修改。当select()返回时,值已全部被修改to reflect the set of file descriptors ready
。因此,每次调用select()之前,您都有to (re)initialize the fd_set
个值。
并且使while循环无限(或增加计数器值),以便它等待读取fds准备就绪。