我想讓UNIX管道正確提示用戶輸入。我必須使用單個管道創建3個子進程。每個子進程都要求用戶輸入一個整數並將其寫入管道。父進程顯示全部三個整數以及每個寫入管道的進程的processid。如何正確地爲用戶輸入提供UNIX管道提示?
#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次。
你已經給出了三個獨立的,不協調的進程無權訪問終端。 *當然*他們交錯輸入和輸出:這就是你告訴他們要做的事情。 – dmckee