Reputation: 9
guys! I am trying to make my first program that uses named pipes or fifo. The client sends to server positive integers. When a negative number is sent, the transmission closes. The server determines the minimum number sent, the maximum number and sends the two values back to the client. The trouble I have is that always the printed max and min are zero and I really don't know how to solve the problem. This is what I have so far:
client.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
main(){
int f1,f2;
int n,a,b;
printf("Give the number: ");
scanf("%d",&n);
while(n >= 0){
printf("Give the number: ");
scanf("%d",&n);
}
f1=open("fifo1",O_WRONLY);
f2=open("fifo2",O_RDONLY);
if(f1<0){
printf("You can't write in the fifo client");
}
if(f2<0){
printf("You can't read from the fifo client");
}
write(f1,&n,sizeof(int));
read(f2,&a,sizeof(int));
read(f2,&b,sizeof(int));
printf("The minimum number is %d\n",a);
printf("The maximum number is %d\n",b);
close(f2);
close(f1);
}
server.c
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int minim=0;
int maxim=0;
int min(int n){
if(n>=0 && minim > n){
minim=n;
}
return minim;
}
int max(int n){
if (n > maxim){
maxim=n;
}
return maxim;
}
main(){
int f1,f2,a,b,n;
f1=open("fifo1",O_RDONLY);
f2=open("fifo2",O_WRONLY);
if(f1<0){
printf("error");
}
if(f2<0){
printf("error");
}
read(f1,&n,sizeof(int));
a = min(n);
b = max(n);
write(f2,&a,sizeof(int));
write(f2,&b,sizeof(int));
close(f1);
close(f2);
}
Upvotes: 0
Views: 2755
Reputation: 2852
This is a pretty simple solution.
For 1, you need to make the fifo with mkfifo. Idk if you did that before in a seperate program or the file already exists, but without that you won't get anything.
For 2, there's no gaurentee that when you're reading on the server that the file has been written to. If the client runs first, then you need to flush your write call in order to ensure that the fifo was written to first. This can be done with fsync(). Once you fsync() on that file descriptor, the file will be written to, and you can gaurentee the values will be there for the server to read. Verify this by having the server read the fifo and then output what it reads.
Upvotes: 2