首页 > 解决方案 > 设置同步文件写入超时而不用 time() 浪费微秒

问题描述

我目前正在将我的 PC 与对时间非常敏感的微控制器连接。事实上,如果我在发送最后一个字节和等待一个字节返回之间有几十微秒的时间可以玩,我会很幸运。

我在 PC 端尝试做的是尽快将数据发送到微控制器。这是我的代码:

#include <stdio.h>
#include <time.h>
#include <fcntl.h>

#define TIMEOUT 5 //give the PC 5 seconds

int main(){
  int nwrite=0;
  int fd=open("/dev/ttyS0",O_NOCTTY | O_WRONLY); //open port
  if (fd > -1){
    int start=time(NULL); //start clock
    while (time(NULL)-start < TIMEOUT && nwrite == 0){
      nwrite=write(fd,"\n",1); //try outputting enter
      if (nwrite < 0){
        close(fd); //close file because writing returned error
        printf("Write Error");
        return -1;
      }
    }
    close(fd); 
    if (nwrite != 0){
       printf("Byte sent out");
    }
  }else{
    printf("Bad file");
  }
  return 0;
}

即使这样可以完成工作,但速度还不够快。这是我从打开到关闭的程序:

13:22:04.160431 open("/dev/ttyS0", O_WRONLY|O_NOCTTY) = 3
13:22:04.160738 time(NULL)              = 1558545724
13:22:04.160913 time(NULL)              = 1558545724
13:22:04.161088 write(3, "\n"..., 1)    = 1
13:22:04.161278 time(NULL)              = 1558545724
13:22:04.161450 close(3)                = 0

我注意到这些时间命令每个处理至少需要 100 微秒。如果发生超时,是否可以使用其他函数代替 time() 中止写入序列?但是该函数需要比 time() 函数执行得更快。

标签: ctimetimermillisecondsseconds

解决方案


推荐阅读