I’ve got two C files, server.c and client.c. The server has to create a fifo file and constantly read in it, waiting for input. The client gets its PID and writes the PID in the fifo.
This is my server file which I launch first:
int main(){
int fd;
int fd1;
int bytes_read;
char * buffer = malloc(5);
int nbytes = sizeof(buffer);
if((fd = mkfifo("serverfifo",0666)) == -1) printf("create fifo error");
else printf("create fifo ok");
if ((fd1 = open("serverfifo",O_RDWR)) == -1) printf("open fifo error");
else{
printf("open fifo ok");
while(1){
bytes_read = read(fd,buffer,nbytes);
printf("%d",bytes_read);
}
}
return(0);
}
And my client file :
int main(){
int fd;
int pid = 0;
char *fifo;
int bytes;
if ((pid = getpid()) == 0) printf("pid error");
char pid_s[sizeof(pid)];
sprintf(pid_s,"%d",pid);
if ((fd = open ("serverfifo",O_RDWR)) == -1)printf("open fifo error");
else {
printf("open fifo ok");
bytes = write(fd,pid_s, sizeof(pid_s));
printf("bytes = %d",bytes);
}
close(fd);
return(0);
}
The two main problems I’m getting are: When I write the pid to the file it returns the number of bytes I wrote so it looks okay but when I check the properties of the fifo file it says 0 bytes. The second problem is the read doesn’t work. If I do a printf before it shows, but after it doesn’t and the read isn’t returning anything it just freezes.
I realise there are a lot of similar posts on the site but I couldn’t find anything that helped.
I’m using Ubuntu and GCC compiler with CodeBlocks.
There are many things wrong here
sizeof(pid)returns the size of the pid value, not its string representation, i.e. it issizeof(int)which is either 4 or 8, depending on your architecture. You then proceed to print it. If this works it works only by luck (you are on a 64 bit machine). The correct way to do is, if you choose to do it at all, is to allocate a suitably large buffer, and use snprintf to make sure you don’t overflow. PIDs fit in 5 digits, so something like this will do:of course, you can skip this step all together and send the raw bytes of the pid instead
Now in the server you make similar mistakes:
sizeof(buffer)returns 4 or 8 again, but you allocated 5 bytes, the correct way to do this, if you want to allocate on the heap (using malloc), is this:alternatively you can allocate on the stack:
sizeof is sort of magical, in that if you pass in an array, it returns the size of the array (8*1) in this case.
When you are reading, you read 5 bytes, which is likely not enough (because you wrote 8 bytes due to the earlier bug), so it would not finish. You should read like this
Also, if you were to actually read and write strings, you’d do something like this:
Note also that read may return less than what was written, and you need to call it again to keep reading…