Basically what i’m trying to do is read a number from a file, increment the value by one, and then write the number back to the same file. Using fork() is supposed to have both processes accessing the file but using locks so they take turns. I keep getting a segmentation fault.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void appendValue(FILE *, int *);
int readValue(FILE *, int *);
void lockFile(FILE *);
void unlockFile(FILE *);
void whatProcess(pid_t *pID);
int main(void) {
pid_t pID;
pID = fork();
int value = 0, counter = 0;
int *valPtr = &value;
pid_t *pidPtr = &pID;
FILE *file = fopen("output.txt", "a+");
lockFile(file);
while(counter < 1000) {
whatProcess(pidPtr);
value = readValue(file, valPtr);
value++;
appendValue(file, valPtr);
rewind(file);
counter++;
}
unlockFile(file);
fclose(file);
printf("\n");
return 0;
}
void whatProcess(pid_t *pID) {
if(*pID > 0) {
printf("\n --- In Parent ---");
} else if(*pID == 0) {
printf("\n --- In Child ---");
} else {
printf("\n --- fork() Failed ---");
}
}
void lockFile(FILE *file) {
int lock;
lock = lockf(fileno(file), F_LOCK, 0);
while(lock != 0) {}
if(lock == 0) {
printf("\nPID %d: Lock Successful", getpid());
} else {
printf("\nPID %d: Lock Unsuccessful", getpid());
}
}
void unlockFile(FILE *file) {
int lock;
lock = lockf(fileno(file), F_LOCK, 0);
while(lock != 0) {}
if(lock == 0) {
printf("\nPID %d: Unlock Successful", getpid());
} else {
printf("\nPID %d: Unlock Unsuccessful", getpid());
}
}
void appendValue(FILE *file, int *value) {
fprintf(file, "%d\n", *value);
}
int readValue(FILE *file, int *value) {
while(!feof(file)) {
fscanf(file, "%d", value);
}
return *value;
}
The
fscanfinreadValueis writing to a non-allocated location. You are passingvaluein as a pointer so there is no need to use the address of operator.Or, even better:
Your current function does not indicate whether it has succeeded or failed. Either add a status return value (zero, -1 are pretty common) or omit error checking and do this instead: