参考文章: http://blog.csdn.net/rl529014/article/details/51336161
http://blog.csdn.net/lin_fs/article/details/7804494
http://blog.csdn.net/querdaizhi/article/details/7478169
以flock函数打开设备文件打开,是独占整个文件
int fd; char com_name[20]={0}; sprintf(com_name,"/dev/ttyS100%d",com_port); // sprintf(com_name,"/dev/ttyS%d",1); // printf("before first open "); fd = open(com_name, O_RDWR|O_NOCTTY|O_NDELAY); // fd = open(com_name, O_RDWR|O_EXCL,0444); if (fd < 0) { perror("open serial port"); return(-1); } if(flock(fd,LOCK_EX|LOCK_NB)==0) { printf("the file was not locked. "); } else { printf("the file was locked. "); close(fd); return -1; } if (fcntl(fd, F_SETFL, 0) < 0) { perror("fcntl F_SETFL "); } if (isatty(STDIN_FILENO) == 0) { perror("standard input is not a terminal device"); } return fd;
以fcntl方式打开设备文件:
int fd; char com_name[20]={0}; sprintf(com_name,"/dev/ttyS100%d",com_port); // sprintf(com_name,"/dev/ttyS%d",1); // printf("before first open "); fd = open(com_name, O_RDWR|O_NOCTTY|O_NDELAY); // fd = open(com_name, O_RDWR|O_EXCL,0444); if (fd < 0) { perror("open serial port"); return(-1); } // printf("first open "); struct flock lock; lock.l_type=F_WRLCK; lock.l_pid=getpid(); lock.l_whence=SEEK_SET; lock.l_start=0; lock.l_len=0; fcntl(fd,F_GETLK,&lock); if(lock.l_type != F_UNLCK){ // printf("%d ", lock.l_type); return -1; } lock.l_type=F_WRLCK; lock.l_pid=getpid(); lock.l_whence=SEEK_SET; lock.l_start=0; lock.l_len=0; if(fcntl(fd, F_SETLKW,&lock) < 0){ perror("fcntl F_SETLKW "); } if (isatty(STDIN_FILENO) == 0) { perror("standard input is not a terminal device"); } return fd;
F_SETLKW 与 F_SETFL的区别是如果有其他锁阻止该锁被建立,则调用进程进入睡眠状态,等待该锁释放。一旦这个调用开始了等待,就只有在能够进行加锁或者收到信号时才会返回。
而且F_SETFL设置方式为fcntl(STDOUT_FILENO,F_SETFL,flags),而非fcntl(fd, F_SETLKW,&lock),无法建立锁机制。 F_SETFL 与 F_SETLKW 使用差别比较大