锁定Linux串行端口 [英] Locking Linux Serial Port

查看:313
本文介绍了锁定Linux串行端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要解决的有关Linux串行端口的问题.我可以打开,读取和关闭端口.但是,我想确保在任何给定时间我都是唯一从该端口进行读/写的人.

I have an issue that I'm trying to solve regarding the serial port in Linux. I'm able to open, read from, and close the port just fine. However, I want to ensure that I am the only person reading/writing from the port at any given time.

我认为在执行open()函数调用之后,这已经为我完成了.但是,我可以在程序的同一端口上多次调用open().我也可以有两个线程同时从同一端口读取.

I thought that this was already done for me after I make the open() function call. However, I am able to call open() multiple times on the same port in my program. I can also have two threads which are both reading from the same port simultaneously.

我尝试使用flock()修复此问题,但我仍然遇到相同的问题.是因为即使每组打开和读取都涉及不同的文件描述符,但两个系统调用都来自同一个pid?作为记录,两个open()调用均返回有效的文件描述符.

I tried fixing this issue with flock() and I still had the same problem. Is it because both systems calls are coming from the same pid, even though there are different file descriptors involved with each set of opens and reads? For the record, both open() calls do return a valid file descriptor.

因此,我想知道是否有任何方法可以解决问题.从我的程序的角度来看,如果在同一端口上两次成功调用open()并没什么大不了的,因为程序员应该意识到它们引起的混乱.但是,我只想确保在打开端口时,我是唯一可以访问该端口的进程.

As a result, I'm wondering if there's any way that I can remedy by problem. From my program's perspective, it's not a big deal if two calls to open() are successful on the same port since the programmer should be aware of the hilarity that they are causing. However, I just want to be sure that when I open a port, that I am the only process with access to it.

感谢您的帮助.

推荐答案

在Linux中,您可以使用TIOCEXCL TTY ioctl阻止其他open()到设备的成功(它们将返回-1errno==EBUSY,设备或资源繁忙).这仅适用于终端和串行设备,但不依赖于咨询性锁定.

In Linux, you can use the TIOCEXCL TTY ioctl to stop other open()s to the device from succeeding (they'll return -1 with errno==EBUSY, device or resource busy). This only works for terminals and serial devices, but it does not rely on advisory locking.

例如:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <fcntl.h>
#include <errno.h>

int open_device(const char *const device)
{
    int descriptor, result;

    if (!device || !*device) {
        errno = EINVAL;
        return -1;
    }

    do {
        descriptor = open(device, O_RDWR | O_NOCTTY);
    } while (descriptor == -1 && errno == EINTR);
    if (descriptor == -1)
        return -1;

    if (ioctl(descriptor, TIOCEXCL)) {
        const int saved_errno = errno;
        do {
            result = close(descriptor);
        } while (result == -1 && errno == EINTR);
        errno = saved_errno;
        return -1;
    }

    return descriptor;
}

希望这会有所帮助.

这篇关于锁定Linux串行端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆