无法在守护程序中打开 ttyUSB 端口

Can't open a ttyUSB port in a daemon

本文关键字:ttyUSB 端口 守护程序      更新时间:2023-10-16

我在linux守护进程中使用端口时遇到问题。我像serHandle_ = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);一样使用fcntl.h中的open,当我在守护进程中使用它时,我得到了0。当我在守护进程之外使用它时,一切都很好。我已经设置了sudo chmod 666 /dev/ttyUSB0

你知道问题出在哪里吗?也许是权限?即使我以超级用户身份启动守护进程,我仍然会从open得到0

下面您可以看到我的类方法的代码片段,它应该初始化守护进程:

Bool DaemonStarter::initialize()
{
  isInitialized_ = false;
  if (workingDirectory_ == "" ||
      !boost::filesystem3::exists(workingDirectory_))
    return false;
  Bool res = true;
  ::setlogmask(LOG_UPTO(LOG_NOTICE));
  ::openlog(name_.c_str(), LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER);
  pid_t pid, sid;
  pid = fork();
  if (pid < 0)
  {
    res = res && false;
    ::exit(EXIT_FAILURE);
  }
  if (pid > 0)
  {
    res = res && true;
    ::exit(EXIT_SUCCESS);
  }
  ::umask(0);
  sid = ::setsid();
  if (sid < 0)
  {
    res = res && false;
    ::exit(EXIT_FAILURE);
  }
  if ((chdir(workingDirectory_.c_str())) < 0)
  {
    res = res && false;
    ::exit(EXIT_FAILURE);
  }
  for (UInt i = ::sysconf (_SC_OPEN_MAX); i > 0; i--)
        ::close (i);
  ::umask(0);
  ::close(STDIN_FILENO);
  ::close(STDOUT_FILENO);
  ::close(STDERR_FILENO);
  isInitialized_ = res;
  return res;
}

openman页面:"open()和creat()返回新的文件描述符,如果发生错误,则返回-1"

0是一个完全有效的文件描述符(对于非守护程序应用程序,它是您的stdin文件描述符)。如果open失败,它将返回-1,所以您的代码运行良好。

当您关闭标准文件描述符(stdin/stdout/stderr)时,这些文件描述符可能会在下一次调用open时重用。所以当open返回0时,这是很正常的。

如果open会失败,它会返回-1

我建议您仔细阅读open手册页面。