我试图让我的程序在每个孩子的时间(每个行包含一个INT)读取一行。每次我执行这个阅读时,它都会继续阅读第一行。FSEEK FTELL读相同的输入
这里是我的代码的基础。
void forkChildren (int nChildren) {
int i;
int size;
int sum = 0;
int tell = 0;
pid_t pid;
for (i = 0; i < nChildren; i++) {
pid = fork();
if (pid == -1) {
/* error handling here, if needed */
return;
}
if (pid == 0) {
char data[10];
FILE * file1;
file1 = fopen("numbers.dat", "r");
fseek(file1, tell, SEEK_SET);
fgets(data, 10, file1);
//fseek(file1, tell, SEEK_SET);
tell += strlen(data);
printf("%d ", tell);
sum = atoi(data);
printf("Sum is: %d \n", sum);
sleep (5);
return;
}
您fseeking到同在所有子进程的文件的开始偏移。如果这不是你想要的,告诉我们你想要什么。 – Fred
即使我认为每次执行阅读时都会增加“告诉”?或者这只会增加对那个孩子的影响? – mschlesinger19
由于(a)每个孩子在不同的(唯一的)文件描述符上操作,并且(b)变量“tell”在每个孩子中是独立的副本,所以它只增加了对每个孩子的讲述。你可以添加一个来告诉其他人(或父母)会知道其中的差异。 – Duck