0
我需要創建三個子進程,每個子進程都從命令行參數中讀取一個字符串,並將字符串寫入單個管道。父母會從管道中讀取字符串,並將其全部三個顯示在屏幕上。我試圖做兩個進程來測試,它打印兩個字符串中的一個,而不是兩個。使用單個管道創建多個子進程
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
char *character1 = argv[1];
char *character2 = argv[2];
char inbuf[100]; //creating an array with a max size of 100
int p[2]; // Pipe descriptor array
pid_t pid1; // defining pid1 of type pid_t
pid_t pid2; // defining pid2 of type pid_t
if (pipe(p) == -1) {
fprintf(stderr, "Pipe Failed"); // pipe fail
}
pid1 = fork(); // fork
if (pid1 < 0) {
fprintf(stderr, "Fork Failed"); // fork fail
}
else if (pid1 == 0){ // if child process 1
close(p[0]); // close the read end
write(p[1], character1, sizeof(&inbuf[0])); // write character 1 to the pipe
}
else { // if parent, create a second child process, child process 2
pid2 = fork();
if (pid2 < 0) {
fprintf(stderr, "Fork Failed"); // fork fail
}
if (pid2 = 0) { // if child process 2
close(p[0]); // close the read end
write(p[1], character2, sizeof(&inbuf[0])); // write character 2 to the pipe
}
else { // if parent process
close(p[1]); // close the write end
read(p[0], inbuf, sizeof(&inbuf[0])); // Read the pipe that both children write to
printf("%s\n", inbuf); // print
read(p[0], inbuf, sizeof(&inbuf[0])); // Read the pipe that both children write to
printf("%s\n", inbuf); // print
}
}
}
我忘了提。我嘗試使用read語句兩次並打印兩次。它打印第一個字符串兩次,而不是兩個字符串。 – Matador89
編輯它包括。 – Matador89
既然你不關注'read()'的返回值,那麼沒有人能猜到你回來的東西。即使您忽略寫入錯誤,您也必須注意'read()'返回的內容;除非查看返回的字節數,否則您不知道有多少數據是有效的。 –