gpt4 book ai didi

c - 如何在c中对文件使用fork()

转载 作者:行者123 更新时间:2023-11-30 17:25:13 24 4
gpt4 key购买 nike

我试图分割一个大文件并使用fork()来读取文件的每个部分。我的程序已经读入文件并使用双向链表计算文件中单词出现的总数。现在我需要将文件分成不同的部分,并在每个部分上使用 fork() 。我已经使用过 mmap(),但我不确定如何使用它,或者如何在此文件上实现 fork()。我见过 fork() 示例,但除了创建子进程并打印 pid 数字之外,它们似乎都没有做任何事情。有谁知道有什么好的例子可以帮助我想做的事情吗?或者我如何实现这部分?

这是我更新的代码的一部分:

             proc_num = atoi(argv[3]); // assign the PROCNUMBER to proc_num as an integer
section = size/proc_num;
// map file to memory and divide workload by passing different
// starting address and stopping address to different processes
if ((addr = mmap(0, size, PROT_READ, MAP_SHARED , file, 0)) == (void *) -1) {
perror("ERROR: Mapping did not work!");
exit(1);
}
char tmp_word[25];
int j, k = 0;
addr = mmap(0, size, PROT_READ, MAP_SHARED , file, 0);
char buf[proc_num][1024];
// Create fork
pid = fork();
if (pid == -1) {
perror("ERROR: Fork failed!");
} else {
for (i = 0; i < proc_num; i++) {
for(j = 0; j < size; j++) {
if(addr[i*size+j] != ' ' && addr[i*size+j] != '\n') {
tmp_word[k]=addr[i*size+j];
k++;
} else {
tmp_word[k]='\0';
// Count the words
count_words(tmp_word, words);
tmp_word[0] = '\0';
k = 0;
}
}
}
}
kill(pid, SIGKILL);
munmap(addr, size);
close(file);
} else {
perror("ERROR: Not a file!");
exit(1);
}

最佳答案

(我不太明白你的代码,fork 在哪里?)

我认为从 2 个兄弟进程读取一个文件不是一个好主意。

来自 fork (2):

 The child inherits copies of the parent’s set of open file  descrip-
tors. Each file descriptor in the child refers to the same open
file description (see open(2)) as the corresponding file descriptor
in the parent. This means that the two descriptors share open file
status flags, current file offset, and signal-driven I/O attributes
(see the description of F_SETOWN and F_SETSIG in fcntl(2)).

这意味着如果您在 fork 进程之前打开文件,进程将共享文件描述符。

如果文件描述符是共享的,并且您想要使用多个进程来读取文件,则每次进程尝试读取文件时都需要查找光标。并且该调用应该受到互斥锁的保护,因此可能不是一个好的解决方案。

关于c - 如何在c中对文件使用fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com