Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a timeout in open/write function

Tags:

c

linux

pipe

fifo

I want to use named fifo channel and I want to implement a timeout when I write in this fifo.

fd = open(pipe, O_WRONLY);
write(fd, msg, len);

Program is blocked by function open, so using the function select will not work. Thanks.

like image 602
Kosterio Avatar asked Sep 14 '14 19:09

Kosterio


2 Answers

use select() and its timeout argument.

like image 185
Jean-Baptiste Yunès Avatar answered Sep 20 '22 01:09

Jean-Baptiste Yunès


Read pipe(7), fifo(7), poll(2)

You might setup a timer or or alarm with a signal handler (see time(7) & signal(7)) before your call to open(2) - but I won't do that - or you could use the O_NONBLOCK flag, since fifo(7) says:

 A process can open a FIFO in nonblocking mode.  In this case, opening
for read-only will succeed even if no-one has opened on the write
side yet, opening for write-only will fail with ENXIO (no such device
or address) unless the other end has already been opened.

However, you need something (some other process reading) on the other side of the FIFO or pipe.

Perhaps you should consider using unix(7) sockets, i.e. the AF_UNIX address family. It looks more relevant to your case: change your code above (trying to open for writing a FIFO) to a AF_UNIX socket on the client side (with a connect), and change the other process to become an AF_UNIX socket server.

As 5gon12eder commented, you might also look into inotify(7). Or even perhaps D-bus !

I'm guessing that FIFOs or pipes are not the right solution in your situation. You should explain more and give a broader picture of your concerns and goals.

like image 29
Basile Starynkevitch Avatar answered Sep 22 '22 01:09

Basile Starynkevitch