Omer Anisfeld
Omer Anisfeld

Reputation: 1302

is there a way of knowing if a file descriptor opened for write has someone listening on the read side?

i have fifo open in one side for read and in the other side for write, the read side close the fd he opened . is there a way of know if the reader closed this fd in the writer side ? i want that the writer will have any notification about whether the reader is ready to read because if not my writer will get blocked on write . writer.c :

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

int main()
{
    int fd;
     char * myfifo = "/tmp/fifo_pipe";
    /* create the FIFO (named pipe) */
    mkfifo(myfifo, 0666);

    /* write "Hi" to the FIFO */
    fd = open(myfifo, O_WRONLY);    

    write(fd, "Hey", sizeof("Hey"));

    /*here is there a posibilty of know that the read side hase close hi's side of the pipe before write? */

    write(fd, "test\n", strlen("test\n"));


    close(fd);

    /* remove the FIFO */
    unlink(myfifo);

    return 0;
}

reader.c :

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#define MAX_BUF 1024

int main()
{
    int fd;
    char * myfifo = "/tmp/fifo_pipe";
    char buf[MAX_BUF];

    /* open, read, and display the message from the FIFO */
    fd = open(myfifo, O_RDONLY);
    read(fd, buf, MAX_BUF);
    printf("Received: %s\n", buf);
    close(fd);

    return 0;
}

Upvotes: 2

Views: 737

Answers (2)

Reeno Joseph
Reeno Joseph

Reputation: 21

You can use lsof system command to check information about files opened by processes. Extract the FD field of the lsof command output and proceed. For more details and example, refer this link

In your case, to get the number of process listening to your fifo, try executing the below system command.

lsof /tmp/fifo_pipe | grep [0-9]r | wc -l

In C you can implement something like this:

int i = 0;
FILE *fp;
char *command = "lsof /tmp/rjfifo | grep [0-9]r | wc -l";

fp = popen(command,"r");
if (fp != NULL){
    fscanf(fp,"%d",&i);
}

fclose(fp);
printf("Number of processes reading /tmp/fifo_pipe = %d \n",i);

Upvotes: 2

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36391

A write in a FIFO with no reader will raise SIGPIPE and eventually returns -1 and errno set to EPIPE.

Upvotes: 2

Related Questions