管()不能很好地工作 - Linux的 [英] Pipe() doesn't work well - linux
问题描述
我试图让使用管道通信的程序。这就是我想要做的事:用户发送正整数。如果用户发送一个负数通信结束。父进程打印的最大数量和最小数。这是我尝试:
I'm trying to make a program using the pipe communication. This is what I'm trying to do: the user sends positive integers. If the user sends a negative number the communication ends. The parent process prints the maximum number and the minimum number. This is what I tried:
#include <unistd.h>
#include <stdio.h>
main(){
int pfd[2];
int buff[200];
pipe(pfd);
if(fork()==0){
close(pfd[0]);
int n;
printf("Give a number: ");
scanf("%d",&n);
while(n >=0 ){
write(pfd[1],&n,1);
printf("Give a number: ");
scanf("%d",&n);
}
exit(0);
}
else{
close(pfd[1]);
read(pfd[0],buff,sizeof(buff));
printf("The parent read %d:",*buff);
wait(0);
}
}
本的printf(父读取%D:,* BUFF);
只打印给我的第一个号码。谁能更好的是我必须做的解释一下吗?如何打印所有的缓存?我写仅1中的缓冲区号,这就是它?如何找到在最大和最小多少?我很困惑! (
This printf("The parent read %d:",*buff);
prints only the first number I gave. Can someone explain to me better what I have to do? How to print all the buffer? Am I writing only 1 number in the buffer and that's it? How do I find the maximum and the minimum number? I am very confused! :(
推荐答案
这是一个方式做什么,我想你想用很少的修改做。
请注意, BUFF
不再是一个数组,我们使用的管材本身作为临时存储为我们打印的数字。
This is a way to do what I think you're trying to do with a very few modifications.
Notice that buff
is no longer an array and that we use the pipe itself as temporary storage as we print the numbers.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int pfd[2];
int buff;
int max,min;
pipe(pfd);
if(fork()==0){
close(pfd[0]);
int n;
printf("Give a number: ");
scanf("%d",&n);
while(n >=0 ){
write(pfd[1],&n,sizeof(n));
printf("Give a number: ");
scanf("%d",&n);
}
exit(0);
}
else {
close(pfd[1]);
printf("The parent read ");
if (read(pfd[0],&buff,sizeof(int))) {
max = buff;
min = buff;
printf("%d",buff);
}
while (read(pfd[0],&buff,sizeof(int))) {
if (buff > max)
max = buff;
else if (buff < min)
min = buff;
printf("%d:",buff);
}
printf("\n");
printf("The maximum value is: %d.\n The minimum value is: %d.\n",max,min);
wait(NULL);
}
}
这篇关于管()不能很好地工作 - Linux的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!