我通过循环链接组织了三个过程:P1-> P2-> P3-> P1。对于这三个链接,我每个都有3个未命名的管道。每个进程从左侧的邻居读取一个整数,并在写入时将一个整数写入邻居。一段时间后,其中一个过程将满足终止条件。这将使该进程关闭其打开的文件描述符并终止。但是,其他进程仍然能够写入当前关闭的fd,并且读取处于阻塞状态。我是否误解了未命名管道的实际工作方式?
void monitor(int *fdr, int *fdw, int pid) {
int A,B,ret,avg;
char send_buf[10], recv_buf[10];
srand((unsigned int) fdr);
A = 20;
close(fdr[1]); close(fdw[0]);
while(1) {
B = rand() % 30;
avg = (A+B)/2;
if (avg > 20) {
printf("P%d computes to high avg. Quit!\n",pid);
break;
}
sprintf(send_buf, "%d", avg);
printf("P%d will write %s\n",pid,send_buf);
ret = write(fdw[1],send_buf,strlen(send_buf)+1);
if (ret == 0) {
printf("P%d cant write. Quit\n",pid);
break;
}
printf("P%d successful write=%d\n", pid, ret);
ret = read(fdr[0], recv_buf,10);
if (ret == 0) {
printf("P%d cant read. Quit\n",pid);
break;
}
printf("P%d reads %s\n",pid,recv_buf);
A = atoi(recv_buf);
}
// Closing filedescriptors should also break the other
// processes out of the while loop
close(fdr[0]);
close(fdw[1]);
printf("P%d closed all descriptors\n",pid);
}