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

查看:24
本文介绍了锁定 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天全站免登陆