我正在阅读http://beej.us/guide/bgipc/html/multi/flocking.html以进行文件锁定,现在我尝试弄清楚如何使用文件描述和文件指针(我需要 fprintf 和 fgets),这个代码实际上可以工作,但我不确定分配给 fdopen 的标志是否正确,这是继续的好方法吗?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#define LINE_MAX 100
#define FILE_READING 1
#define FILE_WRITING 2
int main(int argc, char *argv[])
{
struct flock fl = {F_WRLCK, SEEK_SET, 0, 0, 0};
char s[LINE_MAX];
int fd, fstatus;
FILE *fp;
fl.l_pid = getpid();
if (argc == 1) {
fl.l_type = F_RDLCK;
fstatus = FILE_READING;
} else {
fstatus = FILE_WRITING;
}
if ((fd = open("demo.txt", fstatus == FILE_READING ? O_RDONLY | O_CREAT : O_WRONLY | O_APPEND | O_CREAT, 0600)) == -1) {
perror("open");
exit(1);
}
printf("Press <RETURN> to try to get lock: ");
getchar();
printf("Trying to get lock...\n");
if (fcntl(fd, F_SETLKW, &fl) == -1) {
perror("fcntl");
exit(1);
}
if (fstatus == FILE_WRITING) {
fp = fdopen(fd, "a");
fprintf(fp, "%s\n", argv[1]);
} else {
fp = fdopen(fd, "r");
while (fgets(s, LINE_MAX, fp)) {
printf("%s", s);
}
}
printf("got lock\n");
printf("Press <RETURN> to release lock: ");
getchar();
fl.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("fcntl");
exit(1);
}
printf("Unlocked.\n");
fclose(fp);
close(fd);
return 0;
}