【发布时间】:2016-01-28 14:08:43
【问题描述】:
我必须实现一个程序,其中一个进程将从父进程接收到的数据发送到其子进程,等待子进程将处理后的数据发回,然后将处理后的数据返回给子进程(例如,如果4 个进程的数据流看起来像这样P1->P2->P3->P4->P3->P2->P1)。对于进程间通信的方式,我需要使用管道。这是我计划采取的一种方法:
./child
// Assert argv contains 2 pipe descriptors - for reading
// from parent and for writing to parent, both of type char[]
// I'm not handling system errors currently
int main(int argc, char *argv[]) {
int read_dsc, write_dsc;
read_dsc = atoi(argv[1]);
write_dsc = atoi(argv[2]);
char data[DATA_SIZE];
read (read_dsc, data, DATA_SIZE - 1);
close (read_dsc);
// Process data...
(...)
// Pass processed data further
int pipeRead[2]; // Child process will read from this pipe
int pipeWrite[2]; // Child process will write into this pipe
pipe(pipeRead);
pipe(pipeWrite);
switch(fork()) {
case 0:
close (pipeRead[1]);
close (pipeWrite[0]);
char pipeReadDsc[DSC_SIZE];
char pipeWriteDsc[DSC_SIZE];
printf (pipeReadDsc, "%d", pipeRead[0]);
printf (pipeWriteDsc, "%d", pipeWrite[1]);
execl ("./child", "child", pipeReadDsc, pipeWriteDsc, (char *) 0);
default:
close(pipeRead[0]);
close(pipeWrite[1]);
wait(0);
read (pipeWrite[0], data, DATA_SIZE - 1);
close (pipeWrite[0]);
// Pass data to parent process
write (write_dsc, data, DATA_SIZE - 1);
close (write_dsc);
}
}
我的解决方案的高级描述如下:制作2个管道,一个用于写入子进程,一个用于从子进程读取。等待子进程完成,然后从读取管道中读取数据并将数据传递给父进程。
问题是我不知道这种方法是否正确。我在某处读到不关闭未使用的管道是一个错误,因为它会使操作系统文件描述符混乱,并且一次不应该有很多打开的管道。然而,在这里我们保持未关闭的管道用于从子级读取,如果有n 进程,当进程号n 处理它的数据时,有n 打开的管道(所有父进程都在等待数据返回)。但是我看不到任何其他方法可以解决此问题...
那么 - 我的解决方案正确吗?如果不是,我应该如何解决这个问题?
【问题讨论】:
标签: c operating-system posix