[英]What is the correct way to read from multiple pipes?
因此,在我的程序中,用戶給出了三個參數。 然后,我將其傳送給三個孩子。
兩個孩子都進行自己的計算,然后退出。 最后一個子項顯示結果。
父級等待所有子級完成,然后僅終止程序。
孩子做些什么的總結:
inputs are a, b, c.
child0: c0 = a*b
child1: c1 = b*c
overview: printf("%d %d", c0, c1);
我不知道如何獲取概述以正確打印。 它不斷打印出奇怪的損壞字符或框。
有人對如何正確執行任何建議嗎? 我讀了一本書,但只詳細介紹了單親父母的管道。 這涉及多個孩子,我想那是我感到困惑的地方。 謝謝你的幫助!
代碼如下:
int main(int argc, char *argv[]) {
int fd[4];
int a, b, c, c0, c1, status;
char char0[10];
char char1[10];
pid_t child0;
pid_t child1;
pid_t overview;
// Set argv to ints
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
// Pipe
pipe(fd);
// child0
if((child0 = fork()) == 0) {
close(fd[2]);
c0 = a*b;
sprintf(char0, "%d", c0);
write(fd[0], char0, 10);
close(fd[0]);
exit(0);
}
// child1
if((child1 = fork()) == 0) {
close(fd[2]);
c1 = b*c;
sprintf(char1, "%d", c1);
write(fd[1], char1, 10);
close(fd[1]);
exit(0);
}
// overview
if((overview = fork()) == 0) {
close(fd[0]);
close(fd[1]);
read(fd[2], char0, 10);
read(fd[2], char1, 10);
printf("%s %s", char0, char1); //Prints weird stuff??
close(fd[2]);
exit(0);
}
// Wait for children to finish
waitpid(child0, &status, 0);
waitpid(child1, &status, 0);
waitpid(overview, &status, 0);
exit(0);
}
您聲明管道的代碼是完全錯誤的,管道只有兩個末端,而聲明三個管道則需要如下聲明
pd1[2];
pd2[2];
pd3[2];
從一端可以寫成pd1[1];
從另一端可以讀取pd1[0];
因此您的代碼看起來像
int main(int argc, char *argv[]) {
int fd1[2];
int fd2[2];
int fd1[2];
int a, b, c, c0, c1, status;
char char0[10];
char char1[10];
pid_t child0;
pid_t child1;
pid_t overview;
// Set argv to ints
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
// Pipe
pipe(fd1);
pipe(fd2);
pipe(fd3);
// child0
if((child0 = fork()) == 0) {
close(fd1[0]);
c0 = a*b;
sprintf(char0, "%d", c0);
write(fd1[1], char0, 10);
close(fd[1]);
exit(0);
}
// child1
if((child1 = fork()) == 0) {
close(fd2[0]);
c1 = b*c;
sprintf(char1, "%d", c1);
write(fd2[1], char1, 10);
close(fd2[1]);
exit(0);
}
// overview
if((overview = fork()) == 0) {
close(fd1[1]);
close(fd2[1]);
read(fd1[0], char0, 10);
read(fd2[0], char1, 10);
printf("%s %s", char0, char1); //Prints weird stuff??
//close(fd[2]);
exit(0);
}
// Wait for children to finish
waitpid(child0, &status, 0);
waitpid(child1, &status, 0);
waitpid(overview, &status, 0);
exit(0);
}
此代碼也可能不正確。我剛剛解釋了如何使用管道,請參見管道的打開和關閉,也就是說,在寫入讀取端應關閉而在讀取寫入端時應關閉。
編輯
看到這篇文章並執行小程序,然后逐步了解您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.