所以,基本上我有一段代碼分兩步讀取其中的父進程打印號碼管:從同一管道
for(i=0;i<n;i++)
{
j=i+1;
nwrite=write(pa[1],&j,sizeof(j));
if (nwrite==-1)
{
printf("\nWrite error,pipe closed\n");
exit(-1);
}
if (nwrite==0)
{
printf("\nWrote 0!\n");
break;
}
}
,並從該管道在兩個不同的步驟讀取一個孩子: 它首先讀取所有的偶數,並將其寫入管道pb
:
for(i=0;i<n;i++)
{
nread=read(pa[0],&num,sizeof(num));
if (nread==0)
{
printf("\nNothing to read!\n");
break;
}
if (nread==-1)
{
printf("\nRead error!\n");
exit(-1);
}
if (num%2==0)
{
printf("\nPrinting on pipe pb: %d\n",num);
nwrite=write(pb[1],&num,sizeof(num));
if (nwrite==0)
{
printf("\nNothing to write!\n");
break;
}
if (nwrite==-1)
{
printf("\nwrite error!\n");
exit(-1);
}
}
}
然後它在pause()
和等待另一個進程發送一個signal(SIGUSR1,handler);
接收to後他發出信號,它將繼續它的執行 從管道讀取所有的奇數號碼,並將其寫入pb
管:
for(i=0;i<n;i++)
{
nread=read(pa[0],&num,sizeof(num));
if (nread==0)
{
printf("\nNothing to read!\n");
break;
}
if (nread==-1)
{
printf("\nRead error!\n");
exit(-1);
}
if (num%2==1)
{
printf("\nPrinting on pipe pb: %d\n",num);
nwrite=write(pb[1],&num,sizeof(num));
if (nwrite==0)
{
printf("\nNothing to write!\n");
break;
}
if (nwrite==-1)
{
printf("\nwrite error!\n");
exit(-1);
}
}
}
的事情是,第一read
調用管pa
(從哪裏獲得甚至numebrs)讀取所有管道內容。此後,來自管道pa
的第二個read
調用返回0,因爲所有數字都已被讀取。我想只讀取第一步中的偶數,然後是第二步中的奇數,而我不能這麼做使父母只寫入偶數。 任何提示?謝謝你們。
I am really sorry for my bad indenting, I'm trying my best to solve this issue with my coding style.
你不能。但是您可以從管道讀取數據並將其寫入常規文件,這可以讓您查找。或者您可以讀取數據並將其寫入兩個不同的管道。一個好的練習可能是將奇數寫入一個管道中,您將在同一個線程中讀取這些管道......當您的數據太多時,將會阻止自己,並且瞭解該問題並找出一個很好的練習解析度。 –
這很令人沮喪。我正在學習考試,它明確寫入使用相同的管道,而不是其他文件等東西。我認爲這可能是一個分配錯誤。謝謝您的快速回答。 –
也許這個練習的目的是讓你在內存中存儲奇數,並動態增加內存。 –