diff --git a/src/iniparser.c b/src/iniparser.c index 65c9dd6..d8719c6 100644 --- a/src/iniparser.c +++ b/src/iniparser.c @@ -43,6 +43,18 @@ extern "C" { #endif +/* lock INI file access against concurrent access */ +void ini_file_set_lock (int fd, unsigned int set_lock) +{ + int fd; + struct flock lockinfo; + + memset (&lockinfo, 0, sizeof (struct flock)); + lockinfo.l_type = set_lock ? F_WRLCK : F_UNLCK; + lockinfo.l_pid = getpid(); + fcntl (fd, F_SETLKW, &lockinfo); +} + /* strlib.c following */ #define ASCIILINESZ 1024 @@ -533,11 +545,12 @@ void iniparser_dump_ini(dictionary * d, const char * file_name) if (d==NULL) return; - fd = open (file_name, O_WRONLY | O_CREAT); + fd = open (file_name, O_RDONLY | O_CREAT); if (fd < 0) return; + ini_file_set_lock (fd, 1); - f = fdopen (fd, "w"); + f = fopen (file_name, "w"); if (f == NULL) return; @@ -570,6 +583,9 @@ void iniparser_dump_ini(dictionary * d, const char * file_name) } fclose(f); + + ini_file_set_lock (fd, 0); + close (fd); } /*-------------------------------------------------------------------------*/ @@ -694,8 +710,9 @@ dictionary * iniparser_new(char *ininame) fd = open (ininame, O_RDONLY); if (fd < 0) return NULL; + ini_file_set_lock (fd, 1); - ini = fdopen (fd, "r"); + ini = fopen (ininame, "r"); if (ini == NULL) return NULL; @@ -735,6 +752,10 @@ dictionary * iniparser_new(char *ininame) } } fclose(ini); + + ini_file_set_lock (fd, 0); + close (fd); + return d ; }