我正在學習Linux中的進程管理,我需要通過管道使子進程和父進程通信。我宣佈兩種結構:通過管道寫結構數組
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結構,從第一個到最後一個(在那裏指定)處理數組中的數字,並將計算的統計數據保存到統計結構中。
最相關的部分我的代碼的麻煩有以下幾種(我添加註釋,而不是其他代碼片段來解釋什麼是做OK):
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 - 只有一個進程)。
另外我不知道是否需要等待(NULL),因爲我看到一些不使用它的工作示例。但是,如果我不寫在那裏,父母的printfs將出現在孩子的前面,所以我認爲它不會等待孩子寫入管道。無論如何,沒有它,它就無法工作。
或者,也許結構方法是不是一個好的?
非常感謝您提前!
[不投的malloc()''的返回值。(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – 2012-10-17 17:51:57