FD를 모든 스레드와 공유하므로 파일 설명자를 보호하기 위해 스레드를 만드는 경우 세마포어 또는 뮤텍스를 취해야합니다.
fcntl()은 struct flock structure
을 사용하여 파일 잠금을 정의하고 확인합니다.
주소 공간을 넘어 파일을 보호하려면 뮤텍스가 주소 공간을 초과하여 작동하지 않으므로 구조체 또는 세마포어를 사용해야합니다. 귀하의 참조를 위해, 내가 한 응용 프로그램을 썼습니다.
#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");
}
https://linux.die.net/man/2/flock은 사용하는 플랫폼에서 사용할 수있는 쉬운 옵션 중 하나입니다. – hyde