I need to create a program that calculates the factorial number for one previously declared through main argument using fork()
Sorry for the printfs in portuguese, just ignore them, the point is to divide the number that was set on the arguments and make the calculation using two childrens, after that print the result using the father process. But I'm unable to proceed with the result i've got on the childrens, since they are different processes, can anyone help me solve this?
follows the code i've got so far:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
void filho_01();
void filho_02();
int num=0, total1=1,total2=1, cont=0,num2=0,valor,resultado=0;
int main(int agrc, char** argv) {
pid_t var1, var2;
printf("Calculo de Fatorial com Fork \n\n");
printf("Processo-Pai: Iniciando Execucao.\n\n");
printf("Valor Obtido atraves do Parametro\n");
num = atoi(argv[1]);
num2=num/2;
valor=num;
var1=fork();
if ( var1 == 0 ) filho_01();
var2=fork();
if ( var2 == 0 ) filho_02();
waitpid(var1,&total1,0);
waitpid(var2,&total2,0);
printf("%d",total1);
resultado=total1*total2;
printf("\nProcesso-Pai: Encerrando Execucao.\n");
printf(" \n Fatorial de %d = %d \n",valor, resultado);
}
void filho_01() {
printf("\n\n Filho 1 iniciando:\n");
printf("Calculando...\n");
sleep(3);
for (cont = num; num >num2; num--) {
printf(" filho01: valor = %d \n", num);
total1=total1*num;
}
exit(0);
}
void filho_02() {
printf("\n\n Filho 2 iniciando:\n");
printf("Calculando...\n");
sleep(5);
for (cont = num2; num2 >=1; num2--) {
printf(" filho02: valor = %d \n", num2);
total2=total2*num2;
}
exit(0);
}
Children cannot modify their parent. In the children, the total
variables are separate from the ones in the parent. You simply cannot communicate with the parent this way. Use explicit shared memory, or some other RPC mechanism.