无法在守护程序中打开 ttyUSB 端口
Can't open a ttyUSB port in a daemon
我在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;
}
从open
的man
页面:"open()和creat()返回新的文件描述符,如果发生错误,则返回-1"
0
是一个完全有效的文件描述符(对于非守护程序应用程序,它是您的stdin
文件描述符)。如果open
失败,它将返回-1
,所以您的代码运行良好。
当您关闭标准文件描述符(stdin/stdout/stderr)时,这些文件描述符可能会在下一次调用open
时重用。所以当open
返回0
时,这是很正常的。
如果open
会失败,它会返回-1
。
我建议您仔细阅读open
手册页面。
相关文章:
- Qt Q串行端口未编程设备未关闭
- 如何在C++(VS2010)中设置超时读取USB端口?
- AWS IoT 开发工具包:通过 TCP 端口 443 使用 MQTT
- 在 linux c++ 中没有通过串行端口发送的数据
- 检查串行端口Linux中是否有传入数据(cbInQue for linux)
- 在不传输的情况下更改 Win32 中的串行端口波特率
- 如何将值写入 DIO 模块 AUTOSAR 中的端口?
- grpc 的 ServerBuilder::AddListeningPort() 总是返回 TCP 端口零
- 增强 ASIO 和串行端口异步读取
- 串行端口写入究竟如何从缓冲区实际写入数据?
- 为什么我的 arduino 按钮在 0 和 1 以外的端口上不起作用?
- 如何将参数这些串行端口传递到函数中
- 如何在 Windows 中通过 SSL 端口枚举域控制器
- 无法将套接字绑定到 IPv4 和 IPv6 中的端口
- 从 C/C++ 访问 Android 中的串行端口
- RtMidIn在发行版c++中找不到端口
- Qt两个串行端口发送和接收
- CreateProcess在退出后占用套接字端口(每个套接字地址只允许使用一次)
- 通过串行端口从GPS传感器读取
- 无法在守护程序中打开 ttyUSB 端口