我有以下程序,但在某个时候卡住了。(该程序不会创建更多的子进程,而只会创建一个。有人能帮我吗?
Write a program that counts occurrences of a string as a substring in another string (the two strings are given as arguments on the command line). Every time it checks if the first string appears as a substring starting from a position, checking will be done by a child process (obtained with fork) and the father process is not expecting for the child process to finish to initiate a search starting from a different position - so the verifications are being made in parallel. Each child process returns 0 = did not checked (not shown as substring from that position), 1 = has been verified. After conducting all searches, the father process is expected to finish all sons processes and gather their return codes - this value is will be printed(is the number of times as a substring).
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
char *s1,*s2;
int verificare(char *s1, char *s2, int lungime)
{
pid_t pid;
int i,status;
for (i = 0; i < lungime; i++) {
pid = fork();
switch (pid) {
case -1:
return EXIT_FAILURE;
case 0:
if (strstr(s1, s2) != NULL)
return 1;
else
return 0;
_exit(0);
default:
waitpid(pid, &status, 0);
if (WIFEXITED(status))
printf("Child %d, Return code %d\n", pid,
WEXITSTATUS(status));
return status;
}
}
}
int main(int argc,char **argv){
if (argc!=3){
printf("Too less arg");
return 0;
}
s1=argv[1];
s2=argv[2];
verificare(s1,s2,strlen(s2));
return 0;
}
最佳答案
- 您正在使用
strstr
,它将执行您自己的程序应该执行的操作。您不应该循环遍历以下字符并将它们与模式进行比较吗? - 您的程序基本上是按顺序运行的,因为您正在
wait()
等待子进程在您启动子进程后立即完成。您不应该将所有子 PID 存储在某个数组中,并且只有在所有子 PID 启动后才开始等待吗? - 您的父进程永远不会在子进程中看到
verificare
的返回值,因为您的main
会忽略它并始终返回 0。也许使用exit
从 child 那里返回? - 您的程序无法向用户报告是否找到了匹配项。
我知道这是一项家庭作业,你不应该按照他们要求的方式去做。但是请注意,这不是 fork
的一个很好的用法。可以使用单个处理器检查子字符串的出现,时间与要搜索的字符串的长度成线性关系(使用有限自动机)。所以这个并行算法在这里并没有真正给你买任何东西。
关于c - 使用 fork() 的单词频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27348958/