Hey guys,
I've got a struct array in a header file and at least two pieces of code that access that array.
How do I schedule access for read and write events to that array.
Where do I place my mutex_lock & unlock code?
Thanks for your help,
Tom
header file -> declaration
typedef struct alarm { // creating a alarm data type
char alarm_name[20];
char type[20];
char status[20];
int day;
int month;
int year;
int hour;
int minute;
int second;
} alarm;
// arrays
alarm alarms[10];
write event
// Function saves alarm to file
int save_alarm(alarm *pAl) {
FILE *pFile; // FILE pointer
char *pbuff;
pFile = fopen("Data/alarms.txt", "w"); // create/open file
pthread_mutex_lock(&work_mutex); // lock access to array
if (pFile != NULL) {
pbuff = malloc(50);
sprintf(pbuff, "%s %s %s %02d %02d %d %02d %02d 00",
pAl->alarm_name,
pAl->type,
pAl->status,
pAl->day,
pAl->month,
pAl->year,
pAl->hour,
pAl->minute
);
fputs(pbuff, pFile);
free(pbuff);
fclose(pFile);
pthread_mutex_unlock(&work_mutex);
return 0;
}
else {
printf("\n\tUnable to save alarm");
return 1;
}
}
read event
// Function reads alarms from file and activates them
void open_alarm() {
FILE *pFile = 0;
alCounter = 0;
set_num_records();
// open file in read mode
pFile = fopen("Data/alarms.txt", "r");
if (pFile != NULL) {
for (alCounter = 0; alCounter < rec_num; alCounter++) {
fscanf(pFile, "%s %s %s %02d %02d %d %02d %02d %02d",
&alarms[alCounter].alarm_name,
&alarms[alCounter].type,
&alarms[alCounter].status,
&alarms[alCounter].day,
&alarms[alCounter].month,
&alarms[alCounter].year,
&alarms[alCounter].hour,
&alarms[alCounter].minute,
&alarms[alCounter].second);
}
fclose(pFile);
}
}