I was trying to test named pipe when i encountered this error. I have a file named client.c who writes to a named pipe. And I have a file named server.c who reads from a named pipe and print its value. Looks like there is some issue with server.c
Client code.
//-------CLIENT-----------
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#define FIFO_FILE "MYFIFO"
int main()
{
int fd, ch;
char readbu[80];
int write_byte;
fd=open(FIFO_FILE,O_WRONLY);
while(1)
{
printf("Enter choice \n1.Pepsi\n2.Coke\n3.Limca\n4.Maza\n");
scanf("%d",&ch);
switch(ch)
{
case 1: strcpy(readbu,"Pepsi\0");
write_byte=write(fd,readbu,sizeof(readbu));
break;
case 2: strcpy(readbu,"Coke\0");
write_byte=write(fd,readbu,sizeof(readbu));
break;
case 3: strcpy(readbu,"Limca\0");
write_byte=write(fd,readbu,sizeof(readbu));
break;
case 4: strcpy(readbu,"Maza\0");
write_byte=write(fd,readbu,sizeof(readbu));
break;
default:printf("Invalid");
break;
}
}
return 0;
}
Server code:
// Server code
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#define FIFO_FILE "MYFIFO"
int main()
{
int fd;
char readbuf[80];
char end[10];
int to_end;
int read_bytes;
mknod(FIFO_FILE,S_IFIFO|0640,0);
strcpy(end,"end");
while(1)
{
fd=open(FIFO_FILE,O_RDONLY);
read_bytes=read(fd,readbuf,sizeof(readbuf));
readbuf[read_bytes]='\0';
printf("Rec str = %s of len %d", readbuf,(int)strlen(readbuf));
to_end=strcmp(readbuf,end);
if(to_end==0)
{ close(fd);
break;
}`enter code here`
}
return 0;
}
At server side above code does not print any output.
If i change the printf statements to below then I observe that first iteration it prints blank line and then for other iteration it print old values.
printf("\nRec str = %s of len %d", readbuf,(int)strlen(readbuf));
If i change the printf statements to below then I observe that it prints correct values.
printf("Rec str = %s of len %d\n", readbuf,(int)strlen(readbuf));
I am completely confused how the \n makes so much difference.
I tried to check the value in readbuf using gdb and it actually contains the correct values. Kindly help me understand the trick here.
straceand you'll see what's going on, especially if you usestraceto emit what data your server process actually reads from the pipe.strcpy(readbu,"Pepsi\0");What is this\0doing here exactly?stdoutin line buffered. The contents of the buffer are not displayed on the screen until a\nis printed. So putting the\nat the end of theprintfworks correctly.fd=open(FIFO_FILE,O_RDONLY);in every loop iteration.