【问题标题】:Which OS Concept should be better in such a scenario在这种情况下哪个操作系统概念应该更好
【发布时间】:2017-04-22 07:13:58
【问题描述】:

我正在实现一个 C 代码,其中我有这种情况

我有一个二进制文件code,它在执行时会连续写入一个名为log.txt的文件中。现在同时我打开终端2并再次运行code二进制文件,它也会写入文件日志同时.txt

我想阻止这种情况。我的逻辑是,当第一个二进制文件正在工作并写入文件 log.txt 时,二进制文件的第二个执行实例也需要在 log.txt 上写入,但应该阻止它。我可以实现哪些选项这个?

我计划在 C 编程中为此使用信号量。但如果有人有其他选择,请告诉我

【问题讨论】:

标签: c multithreading operating-system semaphore


【解决方案1】:

如果您正在创建线程,那么您需要使用信号量或互斥锁来保护文件描述符,因为 FD 与所有线程共享。

另一种方法是 fcntl() 使用struct flock structure 来定义和检查文件锁。

当您想要保护超出地址空间的文件时,您应该使用 structflock 或 semaphore,因为互斥锁将无法在地址空间之外工作。供您参考,我写了一个应用程序,看看。

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#define printf(x) printf("%s\n", x)

int main(int argc, char *argv[])
{
    const char filepath[30] = "/Users/darthvader/testlock";
    struct flock *new_wt_lock = (struct flock *) malloc(sizeof(struct flock));
    FILE *fp;

    memset(new_wt_lock, 0, sizeof(struct flock));
    new_wt_lock->l_type = F_WRLCK;
    new_wt_lock->l_len = 0;

    fp = fopen(filepath, "w+");
    if(fp == NULL)
    {
        perror("Error opening file for writing");
        exit(EXIT_FAILURE);
    }
    printf("Attempting to acquire write lock"); 
    if( fcntl(fileno(fp), F_SETLK, new_wt_lock) == -1)
    {
      printf("Unable to acquire lock");
      perror("error");
      exit(EXIT_FAILURE);
    }

    printf("Doing random shit...");
    sleep(25);
    printf("Stopped doing random shit");

    if(fcntl(fileno(fp), F_UNLCK, new_wt_lock) < 0)
    {
        perror("Error releasing lock");
        exit(EXIT_FAILURE);
    }

    printf("Released Lock...Exiting");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2013-04-17
    • 2016-12-24
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    相关资源
    最近更新 更多