我需要创建一个程序,使用fork()
计算先前通过 main 参数声明的一个的阶乘数。对于葡萄牙语中的printfs,请忽略它们,重点是除去在参数上设置的数字并使用两个子项进行计算,之后使用父进程打印结果。但是我无法继续处理我对孩子们的影响,因为他们是不同的过程,任何人都可以帮我解决这个问题吗?
遵循我到目前为止的代码:
#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);
}
答案 0 :(得分:1)
所以几天后我做到了! 我没有评论代码,因为我想它很容易理解 (对于那个很抱歉)。 我确实使用管道进行进程通信。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int product = 1; // global scope variable
// prototypes
int factorial(int, int);
int factorial(int start, int n) {
int product_ = 1;
for ( int i = start; i <= n; i++ ) {
product_ *= i;
}
return product_;
}
int main( void ) {
siginfo_t infop;
pid_t firstSon, secondSon;
__id_t fSon = firstSon, sSon_ = secondSon;
int fd[2], n, fStatus, sStatus;
int middle, factor;
printf( "%s", "Enter a number: " );
scanf( "%d", &n );
if ( n < 2 ) {
printf( "\nFactorial of %d is %s\n", n, "1" );
return EXIT_SUCCESS;
}
if ( pipe( fd ) < 0 ) {
fprintf( stderr, "\nerror pipe" );
exit( EXIT_FAILURE );
}
else if ( (firstSon = fork()) < 0 || (secondSon = fork()) < 0 ) {
fprintf( stderr, "\nfork error\n" );
exit( EXIT_FAILURE );
}
else if ( firstSon == 0 ) {
middle = n / 2;
factor = factorial( 1, middle );
printf( "\n%s: %d", "First process result", factor );
close( fd[0] );
write( fd[1], &factor, sizeof( int ) );
}
else if ( secondSon == 0 ) {
middle = n / 2 + 1;
factor = factorial( middle, n );
printf( "\n%s: %d", "Second process result", factor );
close( fd[0] );
write( fd[1], &factor, sizeof( int ) );
}
else {
waitid(P_PID, fSon, &infop, WEXITED);
close( fd[1] );
read( fd[0], &factor, sizeof( int ) );
product *= factor;
waitid(P_PID, sSon_, &infop, WEXITED);
close( fd[1] );
read( fd[0], &factor, sizeof( int ) );
product *= factor;
printf( "\nFactorial of %d is %d\n", n, product );
}
return EXIT_SUCCESS;
}
答案 1 :(得分:0)
儿童不能修改他们的父母。在子项中,total
变量与父项中的变量分开。你根本无法以这种方式与父母沟通。使用显式共享内存或其他一些RPC机制。