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
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.
For example:
#include
#include
#include
#include
#include
#include
#include
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;
}
Hope this helps.