在这种情况下,哪个 OS 概念应该更好

Which OS Concept should be better in such a scenario

我正在执行一个 C 代码,其中我遇到了这种情况

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

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

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

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

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

如果您想保护地址 space 之外的文件,您应该使用 struct flock 或 semaphore,因为互斥量在地址 space 之外将无法工作。供大家参考我写了一个应用,你看看

#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");
}