尝试将父进程拆分为两个子进程。第一个将计算给定数字的阶乘。第二个只会说 I'm child 2!
完成后,第一个子级将输出计算阶乘所需的时间。让第一个 child split 并完成其工作效果很好。然而,我看不出让老二做任何事。知道我做错了什么吗?
#include <stdio.h>
#include <time.h>
//#include </sts/types.h>
#include <unistd.h>
//prototypes
int rfact(int n);
int temp = 0;
main()
{
int n = 0;
long i = 0;
double result = 0.0;
clock_t t;
printf("Enter a value for n: ");
scanf("%i", &n);
pid_t pID = fork();
if (pID ==0)//child
{
//get current time
t = clock();
//process factorial 2 million times
for(i=0; i<2000000; i++)
{
rfact(n);
}
//get total time spent in the loop
result = ((double)(clock() - t))/CLOCKS_PER_SEC;
//print result
printf("runtime=%.2f seconds\n", result);
}
else if(pID < 0)
{
printf("fork() has failed");
}
else //parent
{
//second fork for child 2
pid_t pID2 = fork();
if (pID2 == 0)
{
execl("child2.o","child2", 20, NULL);
}
else if (pID2 < 0)
{
printf("fork() has failed");
}
else
{
waitpid(0);
}
waitpid(0);
}
}
//factorial calculation
int rfact(int n)
{
if (n<=0)
{
return 1;
}
return n * rfact(n-1);
}
这是 child2.c:
#include <stdio.h>
void main()
{
printf("I'm child 2!");
}
好吧,我在使用 Eclipse 时遇到了问题。我删除了它并重新编译了两个 .c 文件。我使用 execl 指向 child2.o,但它仍然没有执行任何操作
最佳答案
您无法执行 .c 源文件! 您需要编译它并执行生成的二进制文件。
使用脚本语言,通常可以在开头添加 #!/usr/bin/whatever 行,它们将使用该解释器执行,但 C 需要编译,不能被解释。
关于c - 使用 fork() 在 C 中创建两个子进程时出现问题(在 Debian 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15079122/