參考文章: 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\n"); 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.\n"); } else { printf("the file was locked.\n"); close(fd); return -1; } if (fcntl(fd, F_SETFL, 0) < 0) { perror("fcntl F_SETFL\n"); } 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\n"); 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\n"); 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\n", 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\n"); } 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 使用差別比較大