Skip to content

Commit 3f63e6f

Browse files
author
Зишан Мирза
committed
refactor: file read
1 parent 0a9e08b commit 3f63e6f

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

libc/src/time/time_utils.cpp

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,26 @@ static int64_t computeRemainingYears(int64_t daysPerYears,
2727
return years;
2828
}
2929

30+
volatile int lock = 0;
31+
32+
void release_file(FILE *fp) {
33+
lock = 0;
34+
fclose(fp);
35+
}
36+
37+
void acquire_file(FILE *fp, char *timezone) {
38+
while (1) {
39+
if (lock == 0) {
40+
lock = 1;
41+
break;
42+
}
43+
}
44+
45+
if (fgets(timezone, sizeof(timezone), fp) == NULL) {
46+
release_file(fp);
47+
}
48+
}
49+
3050
// First, divide "total_seconds" by the number of seconds in a day to get the
3151
// number of days since Jan 1 1970. The remainder will be used to calculate the
3252
// number of Hours, Minutes and Seconds.
@@ -132,13 +152,18 @@ int64_t update_from_seconds(int64_t total_seconds, struct tm *tm) {
132152

133153
char timezone[128];
134154

135-
FILE *fp;
155+
FILE *fp = NULL;
136156
fp = fopen("/etc/timezone", "rb");
137157
if (fp == NULL) {
138158
// TODO: implement getting timezone from `TZ` environment variable and
139159
// storing the value in `timezone`
140-
} else if (fgets(timezone, sizeof(timezone), fp) == NULL)
160+
} else {
161+
acquire_file(fp, timezone);
162+
}
163+
164+
if (lock == 0) {
141165
return time_utils::out_of_range();
166+
}
142167

143168
// UTC = 0
144169
int offset = 0;
@@ -168,7 +193,7 @@ int64_t update_from_seconds(int64_t total_seconds, struct tm *tm) {
168193
}
169194
tm->tm_hour += offset;
170195

171-
fclose(fp);
196+
release_file(fp);
172197

173198
return 0;
174199
}

0 commit comments

Comments
 (0)