我试图让 UNIX 管道正确提示用户输入。我必须使用单个管道创建 3 个子进程。每个子进程要求用户输入一个整数并将其写入管道。父进程显示所有三个整数以及将每个整数写入管道的进程的 processid。
#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 次之前我不能输入任何内容。