私はLinuxでプロセス管理を学んでおり、子と親がパイプを介して通信する必要があります。2 つの構造体を宣言しました。
typedef struct
{
double min, max, avg; /*Number stats*/
} Stats;
typedef struct {
pid_t pid; /*Process ID*/
int first; /*First number to process*/
int last; /*Last number to process*/
int fd[2]; /*Pipe descriptor*/
Stats stats; /*Stats computed by process*/
}Process_list;
数値の配列からいくつかの統計を計算する (作業を分割する) には、M 個の子プロセスが必要です。次に、子プロセスは Process_list 構造体を読み取り、配列内の番号を最初から最後まで処理し (そこに指定されています)、計算された統計を stats 構造に保存します。
コードの問題に最も関連する部分は次のとおりです (何が正常に行われたかを説明するために、他のコードの代わりにコメントを追加しています)。
int main(int argc, char *argv[])
{
pList=(Process_list *)malloc((M+1)*sizeof(Process_list));
/*Correct allocation is checked*/
int i;
pid_t pid;
for (i=0 ; i<M ; i++) /*M clones*/
{
/*Fork and pipe creation*/
pid = fork ();
pipe(pList[i].fd);
/*If it's the child*/
if ( pid == 0 )
{
pList[i].pid=pid;
printf("CHILD %d: %d a %d\n",i, pList[i].first,pList[i].last);
/*A function here computes stats and saves them OK in the struct*/
/*(e.g. min is saved in pList[i].stats.max, when printed it's a reasonable value)*/
/*Now I need to send the info to the parent*/
ret1=close(pList[i].fd[0]);
/*ret1=0 => OK */
ret2=write(pList[i].fd[1], &(pList[i].stats), sizeof(Stats));
printf("return write: %d\n",ret2);
/*TROUBLE HERE! This isn't even printed. sizeof(Stats)=24 which I think is OK*/
exit(EXIT_SUCCESS);
}
/*Parent*/
else if ( pid > 0 )
{
wait(NULL); /*Is this really neccesary?*/
ret1=close(pList[i].fd[1]);
ret2=read(pList[i].fd[0], &(pList[i].stats), sizeof(Stats));
/*Both ret1 and ret2 = 0*/
printf("[p]Mín: %lf\n Max: %lf\nAverage: %lf\n",pList[i].stats.min,pList[i].stats.max,pList[i].stats.avg);
/*Everything printed here = 0.0000000000*/
}
else /*fork error*/
return -1;
}
したがって、私の問題は、子が統計を完全に計算しているのに、親がそれらを受け取っていないことです。write() 関数は何もしません。これは、M のすべての値に対して発生します (M=1 - 1 つのプロセスのみを含む)。
また、wait(NULL) が必要かどうかもわかりません。これを使用しない実際の例をいくつか見たことがあります。ただ、そこに書かないと親のprintfsが子より先に出てしまうので、子がパイプに書き込むのを待たないだけだと思います。とにかくそれなしでは機能しません。
それとも、構造アプローチが適切ではないのでしょうか?
事前にどうもありがとうございました!