まず、いくつかの魔法を見る準備をしてください。
こんにちは、私はこの問題で過去の時間に不満を抱き、苦労しています。なぜ子プロセスが死ぬのか理解できません。私は基本的に1つの親プロセスと多くの子プロセスを持っています。すべての子供は親とコミュニケーションする必要があり、親はすべての子供とコミュニケーションを取る必要があります。まず始めに、子どもたちは常にread
にしようとしましたが、私の親は何も送信せず、ちょうどwrite
のパイプの最後を閉じて、reads
のブロックを止めました。ここに私のプロセスです(私のマクロdefは5
の子プロセスです)。 パイプの閉鎖にもかかわらず読み取りがブロックされ続けます
2
パイプを指す5 int*
の配列を作成して始めます。親は子供に話をする最初のものを使用し、子供が二1を使用しています を5
子どもたちとそれぞれの子が継続的にread
ループがを死ぬ子どもの死亡を待って終了する必要がありますので、私のコード(S)
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/types.h>
#define PROCESSES 5
int main(int argc, char ** argv) {
int * pipes[PROCESSES];
for (int i = 0; i < PROCESSES; i++) {
pipes[i] = malloc(sizeof(int) * 2);
if (pipe(pipes[i]) == -1) {
perror("Error piping");
exit(1);
}
}
//PIDS we will wait on
int children_pids[PROCESSES];
for (int i = 0; i < PROCESSES; i++) {
int status = fork();
switch(status) {
case -1:
perror("Error forking a child");
exit(1);
case 0:
//Close the pipes we don't need
close(pipes[i][1]);
//Inside the child process, die immediately
char buffer[128] = "";
while (read(pipes[i][0], buffer, 127) > 0) {
//Keep reading and doing nothing
}
printf("Dying\n");
exit(1);
default:
//Parent process, close the pipes we don't need
close(pipes[i][0]);
break;
}
//Parent continue spawning children
children_pids[i] = status;
}
//CLOSE ALL PIPES FROM PARENT TO CHILDREN------------
for (int i = 0; i < PROCESSES; i++) {
if (close(pipes[i][1]) == -1) {
perror("Error closing a pipe");
exit(1);
}
}
//AWAIT CHILDREN DEATHS
for (int i = 0; i < PROCESSES; i++) {
wait(&children_pids[i]);
}
printf("All children have died");
return 0;
}
私はそれが取り除かれたとき、それが正常に動作しますので、死んでから子供をブロックしている子供のread
ループであることを知って。しかし、なぜこれが当てはまるのか分かりません。下の私のループでは、私は明らかにすべてのパイプを閉じ、エラーをチェックします。どうしてこれなの?! read
はまだ私の道で私のreturn;
の目標を達成することができませんでしたか?
各chileは 'dup'ed fd ...を持っています。したがって、「書き込み終了」を閉じると、すべての子プロセスが終了するまで子プロセスfdで終了しません...書き込み終了子プロセスで終了し、参照カウントを1に戻します。 – Myst
@Myst、OPは以下を閉じます。 'close(pipes [i] [1]);' – SergeyA
@SergeyA - それらのうちの1つだけが閉じられます。オペレーションはそれぞれの「i」のために閉じるべきである – Myst