试图将父进程拆分为两个子进程。第一个将计算给定数字的阶乘。第二个只会说I'm child 2!
完成后,第一个孩子将输出计算阶乘所需的时间。让第一个孩子分裂并完成它的工作就很好。但是,我看不到让第二个孩子做任何事情。知道我做错了什么吗?
#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,但它仍然没有做任何事情