基本上我要做的是从文件中读取一个数字,将值加一,然后将数字写回同一个文件。使用 fork() 应该让两个进程都访问文件但使用锁,因此它们轮流进行。我不断收到分段错误。
#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;
}