我之前发布了一条关于using fork() and pipes in C 的问题。我稍微改变了一下设计,以便它读取一个普通的txt文件并对文件中的单词进行排序。到目前为止,这是我想出了:C中的多进程,叉和管道
for (i = 0; i < numberOfProcesses; ++i) {
// Create the pipe
if (pipe(fd[i]) < 0) {
perror("pipe error");
exit(1);
}
// fork the child
pids[i] = fork();
if (pids[i] < 0) {
perror("fork error");
} else if (pids[i] > 0) {
// Close reading end in parent
close(fd[i][0]);
} else {
// Close writing end in the child
close(fd[i][1]);
int k = 0;
char word[30];
// Read the word from the pipe
read(fd[i][0], word, sizeof(word));
printf("[%s]", word); <---- **This is for debugging purpose**
// TODO: Sort the lists
}
}
// Open the file, and feed the words to the processes
file_to_read = fopen(fileName, "rd");
char read_word[30];
child = 0;
while(!feof(file_to_read)){
// Read each word and send it to the child
fscanf(file_to_read," %s",read_word);
write(fd[child][1], read_word, strlen(read_word));
++child;
if(child >= numberOfProcesses){
child = 0;
}
}
其中numberOfProcesses
是一个命令行参数。所以它所做的是读取文件中的每个单词并将其发送给进程。但是,这不起作用。当我在子进程中打印该单词时,它不会给我正确的输出。我正在向管道正确写入/读取单词吗?
我强烈怀疑这是主要问题 - 您绝对需要同步您的并发进程,否则输出将相互“交错”(即“混乱”)。 – paulsm4
这是一个任务。我对C编程和在Linux环境下工作都很陌生。所以是的,我必须用流程来做到这一点。用C#写这个不到2个小时。但请注意,我使用Emacs作为编辑器,而不是Visual Studio,因此整个调试过程是一场噩梦。 – PoweredByOrange
@ programmer93如果您习惯于IDE,那么您最好使用Eclipse和CDT。 –