簡體   English   中英

與fgets和fprintf兼容的文件鎖定

[英]File Locking compatible with fgets and fprintf

我正在閱讀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;
}

根據文檔fdopen()使用與fopen()相同的模式參數,據我所知,您已經正確使用了它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM