C-文件锁定与fgets和fprintf兼容



我正在阅读http://beej.us/guide/bgipc/html/multi/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, "%sn", argv[1]);
    } else {
        fp = fdopen(fd, "r");
        while (fgets(s, LINE_MAX, fp)) {
            printf("%s", s);
        }
    }
    printf("got lockn");
    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;
}

根据文档,fdopen()使用与fopen()相同的模式参数,因此据我所知,您已经正确使用了它们。

相关内容

  • 没有找到相关文章

最新更新