poly
poly

Reputation:

IPC with FIFO in C under linux

I've been trying to implement IPC with FIFO, I've made the below and it seems to be working fine, tested few times and it looks good to me.

The question is what do I need to take care of, I know the that read and write will be atomic as I'm gonna be writing way below the PIPE_BUF.

I've run it like this

./writer

./reader ./reader

and I saw that that the readers are working fine, for example first reader reads 1 then second reader reads 2 and 3 then first reader reads 4 and so on.

please note that I've found the code in here and I modified it.

writer.c

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
    int main()
    {
    int fd,fd1;
    fd=open("fifo1",O_WRONLY);
    int data = 1;
    while (1){
    write(fd,&data,sizeof(int));
    usleep(10);
    data++;
    }

    //printf("File Content :%s",s1);
    }

reader.c

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
    int main()
    {
    int fd,fname;
    mkfifo("fifo1",0600);
    fd=open("fifo1",O_RDONLY);
    int d = 0;
    while(read(fd,&d,sizeof(int))!=0)
    {
    printf("%d\n",d);
    usleep(10);
    }
    close(fd);
    }

Upvotes: 2

Views: 9847

Answers (1)

If some reader process is starved, it would become blocked on the read syscall, and the writer would eventually be scheduled by the kernel and will write something. The PIPE_BUF limit matters only for the maximal size of a single message (e.g. a read, and you won't reach that size).

Symmetrically, if writer writes a lot, the fifo buffer gets full (above PIPE_BUF) and the write syscall is blocked in the writer process. Eventually the scheduler will run the reader.

See read(2) and write(2) man pages. Learning about poll(2) could also be helpful when you want to multiplex. See also fifo(7).

PIPE_BUF is a limit on each atomic read and write. Bigger reads and writes could be done only partly. The kernel guarantee that if a read or write operation can be achieved on less than PIPE_BUF bytes (i.e. when such an amount of bytes is available!) it will be done in whole on pipes and related file descriptors (eg. FIFOs).

Read the advanced unix programming and/or advanced linux programming books

Upvotes: 1

Related Questions