其他分享
首页 > 其他分享> > 无法理解select()系统调用

无法理解select()系统调用

作者:互联网

我正在使用FIFO和select()系统命令运行测试.这个想法是:

>进程1应该使用select()命令等待来自FIFO的消息
>如果没有消息进入,进程一应该每隔5秒唤醒并说“还没有”
>如果收到消息,它应该唤醒,打印消息,然后终止

所以这里是代码注意我正在进行错误检查以节省空间:

//process 1's code
int main()
{
  int fd, ret;
  fd_set rfds;
  char buffer[100] = {0}; 
  char * myfifo = "/tmp/myfifo";
  struct timeval tv;

  tv.tv_sec = 5;  // 5 second sleep
  tv.tv_usec = 0;

  mkfifo(myfifo, 0666); //Make the fifo

  fd = open(myfifo, O_RDONLY);
  FD_ZERO(&rfds);    // clear the flags
  FD_SET(fd, &rfds); // set "read" on fd

  while((ret = select(fd+1, &rfds, NULL, NULL, &tv)) <= 0) //should be 1 when we're ready to read
  {
     FD_ZERO(&rfds);     //I believe we should clear/reset these every time?
     FD_SET(fd, &rfds);
     printf("Nothing yet...%d\n",ret);
     fflush(stdout);
  }
  n = read(fd, buffer, 100);
  printf("I got a read of %d bytes\nIt was %s\n",n, buffer);

  unlink(myfifo);

  return 0;
}

一旦我启动并运行了1个进程,我等待10秒然后开始进程2:

//Process 2's code
int main()
{
  int fd, n, ret;
  fd_set rfds;
  char buffer[100] = {0};
  char * myfifo = "/tmp/myfifo";
  fd = open(myfifo, O_WRONLY);

  printf("What would you like to send?\n");
  fgets(buffer, 100, stdin);
  write(fd, buffer, strlen(buffer));

  close(fd);
  return 0;
}

我期待看到类似的东西:

Nothing yet...0
Nothing yet...0
I got a read of X bytes
It was <some string>

相反,我什么都没看到,直到我输入内容并点击进入第二个进程,进程一正确返回字符串…但为什么循环不打印消息?

解决方法:

正如您在Linux上一样,您可能希望将O_NONBLOCK添加到阅读器端的open()调用中.详情请见man 7 fifo.

标签:c-3,fifo,linux,posix,file-descriptor
来源: https://codeday.me/bug/20190723/1511670.html