【发布时间】:2022-02-03 08:29:42
【问题描述】:
我正在尝试在 C 中实现一个代码,它有一个文本文件作为输入,文本文件中的每一行都包含一个从 2 到 N 递增顺序的数字,我想使用埃拉托色尼筛法识别素数。我想为此使用 Fork()。
我找到了一种使用管道的方法,但我想知道是否有一种方法可以使用不带管道的 fork 来实现。
这是我的代码(我不是最好的,所以有点乱)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
//Delete multiples
void delete(int p, int r, int w){
int i;
while(read(r, &i, sizeof(i))){
if(i % p != 0){
write(w, &i, sizeof(i));
}
}
}
void primes(int r){
int p;
pid_t pid;
if(read(r, &p, sizeof(p))){
int primePipe[2];
pipe(primePipe);
printf("%d\n", p); //Printing out the numbers
pid = fork();
if(pid < 0){ // Error with fork
fprintf(stderr, "Fork Failed");
exit(1);
}else if(pid){ //Child
close(primePipe[1]);
primes(primePipe[0]);
}else{ //Parent
close(primePipe[0]);
delete(p, r, primePipe[1]);
close(primePipe[1]);
}
}
}
int main(int argc, char *argv[]) {
int num;
int pd[2];
pid_t pid;
pipe(pd);
char fileName[200];
//Take a file as input
printf("Enter the name of the file: \n");
scanf("%s",fileName);
FILE* file = fopen(fileName, "r");
if (! file ){
printf("Error, the file cannot be read.\n");
exit(-1);
}
pid = fork();
if (pid < 0) { //Error with fork
fprintf(stderr, "Fork Failed");
exit(1);
return 1;
}else if(pid){ //Child
close(pd[1]);
primes(pd[0]);
}else{ //Parent
close(pd[0]);
while (fscanf(file, "%d", & num) == 1 ){ //Going through the file
write(pd[1], &num, sizeof(num));
}
close(pd[1]);
}
exit(0);
}
【问题讨论】:
标签: c pipe fork primes sieve-of-eratosthenes