我正在实现一个场景,其中父进程分叉许多子进程,这些子进程进行计算并通过管道将结果返回给父进程。由于子进程必须使用外部库的数据类型(GMP 的 mpz_t 类型),因此它们需要使用该库自己的输出流函数。此函数允许文件指针作为输入而不是文件描述符。因此,我获得了管道写入端的文件指针,并用于写入一些数据。下面给出了代码的子进程和父进程部分:
pid_t ppid;
ppid = getpid();
struct sigaction sig;
sigemptyset(&sig.sa_mask);
sig.sa_flags = 0;
sig.sa_handler = sig_usr;
if(sigaction(SIGINT,&sig,NULL) != 0)
printf("\ncan't catch SIGINT\n");
if(sigaction(SIGUSR1,&sig,NULL) != 0)
printf("\ncan't catch SIGINT\n");
pid_t childpid;
pid_t childpids[operand1Length*operand2Length];
int childPIDInd = 0;
//Create pipe: (must do before fork() so FDs are inherited by child)
int pipefd[2]; //array to hold pipe FDs
pipe(pipefd);
for(i=operand2Length-1, k=0; i>=0; i--, k++){
for(j=operand1Length-1, l=0; j>=0; j--, l++){
childpid = fork();
switch(childpid){
case -1:
//fork error
perror("fork failed!\n");
exit(EXIT_FAILURE);
case 0:
close(pipefd[0]);
subOperandLength = subOperands[k].length;
FILE* fp = NULL;
fhe_mul(subOperands[k].operand[subOperandLength-1-k-l], num1->operand[j], num2->operand[i], pk);
while(WritePermit); // unless parent process sends a signal any child process cannot enter this critical section.
fp = fdopen(pipefd[1], "w");
if(fp == NULL)
fprintf(stderr, "Child Process #%d file pointer is NULL. Error: %s. Pipe FD: %d\n", getpid(), strerror(errno), pipefd[1]);
//Except the child process which enters the critical section first,
//for all other child processes fp is NULL.
gmp_fprintf(fp, "%Zd\n", subOperands[k].operand[subOperandLength-1-k-l]);
gmp_fprintf(fp, "%d\n", k);
gmp_fprintf(fp, "%d\n", subOperandLength-1-k-l);
fflush(fp);
fclose(fp);
kill(ppid, SIGUSR1);
exit(EXIT_SUCCESS);
default:
childpids[childPIDInd] = childpid;
childPIDInd++;
close(pipefd[1]);
if(i == 0 && j == 0){ // last child was created
kill(childpids[0], SIGINT);
mpz_t deneme;
mpz_init(deneme);
FILE* fs = fdopen(pipefd[0], "r");
int forIndex, pidIndex;
for(forIndex=0, pidIndex=1; forIndex<4; forIndex++, pidIndex++){
while(WritePermit2);
while((gmp_fscanf(fs, "%Zx\n", &deneme)) > 0){
gmp_fprintf(stdout, "Parent Process #%d: %Zd\n", getpid(), deneme);
}
kill(childpids[pidIndex], SIGINT);
WritePermit2=1;
}
fclose(fs);
int status;
int i=0;
int clean = 1;
while (i < operand1Length*operand2Length) {
wait(&status);
if(!WIFEXITED(status))
clean = 0;
i++;
}
if(!clean){
printf("I am having some problems with my children! :'(\n");
exit(EXIT_FAILURE);
}
}
}
}
仅对其中一个子进程fp有效。然后,不知何故,它变为 NULL,因此 gmp_fprintf 在其他子进程中引发错误。
请不要犹豫,询问您是否需要有关代码的更多详细信息。提前谢谢你的帮助!