UNIX パイプがユーザー入力を正しく要求するようにしようとしています。1 つのパイプを使用して 3 つの子プロセスを作成する必要があります。各子プロセスは、ユーザーに整数を入力するように求め、それをパイプに書き込みます。親プロセスは、3 つの整数すべてと、それぞれをパイプに書き込んだプロセスのプロセス ID を表示します。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char argv[]) {
int input = 0;
int pd[2];
int i =0;
int buffer[100];
int output = 0;
if (pipe(pd) == - 1) {
fprintf(stderr, "Pipe Failed");
}
for (i=0; i<3; i++) {
if (fork() == 0) { // child process
printf("\nMy process id is: %d", getpid());
printf("\nEnter an integer: ");
scanf("%d", &input);
if (write(pd[1], &input, sizeof(int)) == -1) {
fprintf(stderr, "Write Failed");
}
return (0); // Return to parent. I am not really sure where this should go
} // end if statement
} // I am not quite sure where the for loop ends
// Parent process
close(pd[1]); // closing the write end
for (i = 0; i < 3; i++) {
if (read(pd[0], &output, sizeof(int) )== -1) {
fprintf(stderr, "Read failed");
}
else {
buffer[i] = output;
printf("Process ID is: %d\n", pid);
}
}
printf("The numbers are %d, %d, %d", buffer[0], buffer[1], buffer[2]);
return(0);
}
編集後、出力として得られるようになりました:
My process id is: 2897
Enter an integer: My process id is: 2896
Enter an integer:
My process id is: 2898
Enter an integer: 4
Process ID is: 2898
78
Process ID is: 2898
65
Process ID is: 2898
The numbers are 4, 78, 65
これははるかに近いですが、親が子プロセスを待つようにする方法はまだわかりません。各番号をプロセス ID とともに出力しようとすると、最新のプロセス ID のみが出力されます。
すべての printf ステートメントは scanf ステートメントの前に実行されるため、プロンプトが 3 回表示されるまで何も入力できません。