c - Locking Linux Serial Port -


i have issue i'm trying solve regarding serial port in linux. i'm able open, read from, , close port fine. however, want ensure person reading/writing port @ given time.

i thought done me after make open() function call. however, able call open() multiple times on same port in program. can have 2 threads both reading same port simultaneously.

i tried fixing issue flock() , still had same problem. because both systems calls coming same pid, though there different file descriptors involved each set of opens , reads? record, both open() calls return valid file descriptor.

as result, i'm wondering if there's way can remedy problem. program's perspective, it's not big deal if 2 calls open() successful on same port since programmer should aware of hilarity causing. however, want sure when open port, process access it.

thanks help.

in linux, can use tiocexcl tty ioctl stop other open()s device succeeding (they'll return -1 errno==ebusy, device or resource busy). works terminals , serial devices, not rely on advisory locking.

for example:

#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;     }      {         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;         {             result = close(descriptor);         } while (result == -1 && errno == eintr);         errno = saved_errno;         return -1;     }      return descriptor; } 

hope helps.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -