gpt4 book ai didi

c++ - 无法在守护进程中打开 ttyUSB 端口

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:43 24 4
gpt4 key购买 nike

我在 Linux 的守护进程中使用端口时遇到问题。我使用 fcntl.h 中的 open 就像 serHandle_ = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY); 我得到了 0 作为我在守护进程中使用它时的结果。当我在守护进程之外使用它时,一切正常。我设置了 sudo chmod 666/dev/ttyUSB0

您知道问题出在哪里吗?也许权限?即使我以 super 用户身份启动守护程序,我仍然会得到 0 作为 open 的结果。

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

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,因此您的代码工作正常。

关于c++ - 无法在守护进程中打开 ttyUSB 端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17882234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com