【发布时间】:2015-01-31 09:34:53
【问题描述】:
我正在尝试找到一种方法使该算法同时运行并同时运行。到目前为止,它只有 1 个 for 循环读取每个文件,然后为每个文件创建一个进程。
我相信这个算法是按顺序运行的,这不是我想要的...... 我考虑过创建一个外部 for 循环,在其中放置 wait(null) 和 read 命令。但是当我尝试它不起作用时,没有产生输出。目前我在父进程中有 wait(null) 命令。
有什么建议吗?
代码:
int main(int argc, char *argv[])
{
// ATTRIBUTES //
int freq[argc-1], ipc[argc][2], nbytes, i;// freq of words, pipes, counters
ssize_t errorfi;
char readbuffer[9999];
char** k = malloc(50);
char** op = malloc(50);
if(argc == ONE) { // there are no files given, throw error and close
fprintf(stderr, "There are no files found from %s\n", argv[0]);
exit(0);
}
for(i = 1; i < argc; i++) // creates pipes for ipc
pipe(ipc[i]);
pid_t pids[argc-1]; // array of pids
for(i = 1; i < argc; i++) { // reads input after position 0(a.out)
pid_t pid = fork(); // creates process
pids[i-1] = pid;
if( pid < 0 ) { // bad fork process: error
perror("bad fork");
exit(0);
}
else if(pid > 0) { //parent process
close(ipc[i][1]);
wait(NULL);
nbytes = read(ipc[i][0], readbuffer, sizeof(readbuffer));
if(nbytes > 0)
printf("%s\n", readbuffer);
}
else if(pid == 0) { // child process
close(ipc[i][0]);
k = inputReader(argv[i]); // finds filename,w1,w2,w3,uniqueWords
char info[50] = "";
strcat(info, k[0]);
strcat(info, " ");
strcat(info, k[1]);
strcat(info, " ");
strcat(info, k[2]);
strcat(info, " ");
strcat(info, k[3]);
strcat(info, " ");
strcat(info, k[4]);
int uniqueWordint = atoi(k[4]);
freq[i-1] = uniqueWordint; // freq of all uniqueWords
errorfi = write(ipc[i][1], info, strlen(info)+1); // writes info to pipe i
if (errorfi < 0 ) {
fprintf(stderr, "error found when writing in pipe errofi: %d\n", errorfi);
exit(0);
}
exit(0); // close process
} // closes child process
} // closes for-loop for each process
for(j = 0; j < argc-1; j++) {
wait(2); // if i put read command here it won't work
}
return(0); // close main
}
【问题讨论】:
-
你是
strcat()ing 到一个未初始化的字符数组char info[50];引发未定义的行为。将后者更改为char info[50] ="";。 -
@geforce:这与这个问题无关,但我看到你删除了你之前的问题“使用 pthreads 在 C 中的文件中同时查找单词”。在您删除它之前,我修复了您的一些代码:gist.github.com/anonymous/83338defb71302c4ce36。它仍然很丑陋,并不适用于所有边缘情况,但至少你不应该再遇到段错误。
-
感谢您的尝试...但它仍然在 dataset2.txt 上崩溃,现在它没有为 dataset1.txt 打印正确的输出
-
嗨蒂姆,感谢编辑的代码。我能够根据您的代码进行审查并修复我的主要功能中的某些内容,因此现在一切正常并已排序。此外,我正在摆脱数组并用指针替换。
-
此外,实际问题出在 findWords()... 并且是我的数组 allWords 它没有足够的内存,这就是其他文本文件不起作用的原因。调试后我了解到这是问题所在,所以我将其设为指针并将其设置为更多内存@TimM。
标签: c linux concurrency fork system-calls