tlock.c

来自「this gives details of the network progra」· C语言 代码 · 共 62 行

C
62
字号
#include <stdio.h>#include <unistd.h>#include <fcntl.h>/* File locking subroutines */int lock_fd(int fd) {  struct flock fl;  fl.l_type=F_WRLCK;  fl.l_start = 0;  fl.l_whence=SEEK_SET;  fl.l_len=0;  return(fcntl(fd,F_SETLKW,&fl));}int unlock_fd( int fd) {  struct flock fl;  fl.l_type=F_WRLCK;  fl.l_start = 0;  fl.l_whence=SEEK_SET;  fl.l_len=0;  return(fcntl(fd,F_UNLCK,&fl));}main() {  char c;  FILE *f;  f = fopen("foo","r+");  if (f==NULL) {    printf("Error - can't open the file\n");    exit(1);  }  printf("Locking\n");  if (lock_fd(fileno(f))>=0) {    printf("GOT IT\n");  } else {    printf("CAN'T LOCK FILE\n");    exit(1);  }  read(0,&c,1);  printf("Unlocking\n");  if (unlock_fd(fileno(f))>=0) {    printf("DONE\n");  } else {    printf("CAN'T UNLOCK FILE\n");    exit(1);  }  fclose(f);}  

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?