我试图理解“fork”是如何工作的。我写了一个小程序来解决这个问题,但执行对我来说似乎很奇怪。事实上,“maximum Final”出现了几次,而它位于递归调用的函数“compute”之上。你能解释一下原因吗?
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
ecrire_fils(int nb, char* name) // function to write in a file
{
...
}
lire_pere(int* j, char* name) // function to read a file
{
...
}
int max(int * tab, int debut, int fin) // find the max in an array
{
..
}
int tab[] = {2,4,5,4,1,2,1,2,255,125};
int seuil = 3;
int maximum;
int compute(int * tab, int debut, int fin);
int main(){
printf("\n \n maximum final: %d", compute(tab, 0,9));
return 0;
}
int compute(int * tab, int debut, int fin) {
int pid1, pid2, status;
int milieu = (fin + debut) /2;
char name1[20] = "fic1_";
char name2[20] = "fic2_";
char buffer[100];
sprintf(buffer, "%d", getpid());
strcat(name1, buffer);
strcat(name2, buffer);
if (fin - debut <= seuil) // recherche séquentielle du max
return max(tab, debut, fin); // on s'arrête là et on renvoit le maximum: on n'écrit pas dans un fichier et aucun fichier ne sera lu
pid1 = fork();
if (pid1 == 0) // actions fils1, s'occupe du debut au milieu
{
maximum = compute(tab, debut, milieu); // on récupère la valeur du max des fils
sleep(1);
ecrire_fils(maximum, name1); // on écrit cette valeur dans un fichier qui sera lu par le père
}
else
{
pid2 = fork();
if (pid2 == 0) // actions fils2, s'occupe du milieu à la fin
{
maximum = compute(tab, milieu, fin);
sleep(1);
// on écrit le résultat dans le fichier
ecrire_fils(maximum, name2);
}
else // actions père
{
int j1 = 0, j2 = 0;
waitpid(pid1, &status, 0);
lire_pere(&j1, name1);
waitpid(pid2, &status, 0);
lire_pere(&j2, name2);
printf("\n fils1: %d, fils2: %d (début = %d milieu = %d fin =%d)", j1, j2, debut, milieu, fin);
sleep(1);
if (j1>j2)
return j1;
return j2;
}
}
}
最佳答案
来自您评论的 MCVE(进行了一些小的修复):
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("\n %d : pouet", getpid());
int pid = fork();
printf("\n %d : plop", getpid());
if (pid >0)
printf("\n %d : chouette", getpid());
printf("\n");
return 0;
}
父打印 pouet
并且不会刷新缓冲区(严格来说,它部分刷新 - 这就是为什么你在缓冲区的开头只看到一个空行输出)。子级继承父级的精确副本,包括 stdout 缓冲区中剩余的内容。当 child 打印的时候,这个内容也会被打印。
请注意,如果将格式字符串从 "\n..."
更改为 "...\n"
,该示例将按预期工作。
关于c - 试图理解 c 中的 fork() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41383473/