我知道这是灾难的根源。我实际上使用共享变量让它工作。
但这是作业,老师肯定希望我们把许多进程使用不同的文件指针写入同一个文件。我一整天都在尝试,但收效甚微,但我就是找不到失败的原因。
我已经通过以下方式解决了这个问题:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int status;
int process_count = 0;
do
{
int from = (n / np) * (process_count) + 1;
int to = (n / np) * (process_count + 1);
if (fork() == 0)
{
FILE *aux;
aux = fopen("./parciais.txt", "w");
fseek(aux, sizeof(int) * process_count, SEEK_SET);
int sum = 0;
int i = from;
while (i <= to)
{
int square = i * i;
sum += square;
i++;
}
long int where_am_i = ftell(aux);
printf("I am process %i writing %i on byte: %li\n", process_count, sum, where_am_i);
fwrite(&sum, sizeof(int), 1, aux);
fclose(aux);
exit(1);
}
else
{
wait(&status);
process_count++;
}
} while (process_count < np);
FILE *aux;
aux = fopen("./parciais.txt", "r");
int sum;
for (int i = 0; i <= np - 1; i++)
{
fseek(aux, sizeof(int) * i, SEEK_SET);
long int where_am_i = ftell(aux);
int read;
fread(&read, sizeof(int), 1, aux);
printf("I am reading %i at byte: %li\n", read, where_am_i);
sum += read;
}
}
我希望输出是这样的:
I am process 0 writing 98021 on byte: 0
I am process 1 writing 677369 on byte: 4
I am process 2 writing 1911310 on byte: 8
I am reading 98021 at byte: 0
I am reading 677369 at byte: 4
I am reading 1911310 at byte: 8
但是我得到:
I am process 0 writing 98021 on byte: 0
I am process 1 writing 677369 on byte: 4
I am process 2 writing 1911310 on byte: 8
I am reading 0 at byte: 0
I am reading 0 at byte: 4
I am reading 1911310 at byte: 8
这意味着,出于某种原因,只有最后一个值被写入。
我一直在用头撞墙,我就是找不到问题在哪里...有人可以帮帮我吗?
最佳答案
问题是由于 fopen("./parciais.txt", "w")
:
"w": "创建一个用于写入的空文件。如果已存在同名文件,则删除其内容并将该文件视为一个新的空文件。"
试试用“a”代替!
("追加到一个文件。写入操作,在文件末尾追加数据。文件不存在则创建。")
正如另一个答案中提到的,“a”参数也不够。该文件必须创建一次,因此在主进程中创建,然后以“r+b”模式访问以使 fseek 正常工作!
关于c - 两个进程写入同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621013/