1

I have two processes, first reading from stdin and writing to FIFO file, second is waiting for message from FIFO file.

I am using this program structure:

while(run)
{
  fgets(string, sizeof(string), fp);
}

and when the sentinel (run) change to 0 to stop process, it didn't really stop because it stuck in fgets() function. How can I solve it?

I want program to waits for the message when sentinel change to 0 then immediately stop the program.

roottraveller
  • 7,942
  • 7
  • 60
  • 65
Piter _OS
  • 105
  • 2
  • 11
  • 1
    The common way to do this is to use `select` to wait for input before calling `fgets`. To break out early, clear `run` and then send a signal to the process. The signal will interrupt `select`, it will go back to the top of the loop, see that `run` has cleared and will thus exit. – kaylum Jan 11 '16 at 04:52
  • Can you tell how it will look like in this particular case ?? – Piter _OS Jan 11 '16 at 04:56
  • Another option is to use a signal handler to clear `run`. If the handler is installed without `SA_RESTART` flag, its delivery will interrupt any blocking read/write syscalls in the same thread. Personally, I'd use low-level (unistd.h) I/O, nonblocking, and select(), though. – Nominal Animal Jan 11 '16 at 05:13
  • What would cause `run` to change? – Jean-Baptiste Yunès Jan 11 '16 at 05:16
  • i change run with the signal. Am i right that program return to to place where signal appears ?? – Piter _OS Jan 11 '16 at 05:48
  • 1
    Have you added `volatile` in the declaration of `run`? – nalzok Jan 11 '16 at 07:48
  • @sun qingyao You are the Man :) it works almost all now, in some cases it don't stop. But when i gave volatile it really helps :) – Piter _OS Jan 11 '16 at 18:58

1 Answers1

0

I think here your fifo is opened in Blocking mode, So in fgets() in read call if data is not available that call will be blocked till fifo has some new data.

SO to avoid this open FIFO in non blocking mode by using O_NONBLOCK in open call.

Read more here . http://www.tldp.org/LDP/lpg/node19.html

This way if no data is available fgets with return with error instead of stucking that call. In next while loop check,run will be 0 so it come out from this loop.

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
  • to open fifo i use fopen() function. Can i set something like this in fopen ?? – Piter _OS Jan 11 '16 at 05:15
  • See this http://stackoverflow.com/questions/580013/how-do-i-perform-a-non-blocking-fopen-on-a-named-pipe-mkfifo Using open() open fifo and then using fdopen() convert file discriptor to file pointer and then perform all file operation – Jeegar Patel Jan 11 '16 at 05:20
  • i got this problem when i'm using fdopen: Segmentation fault (core dumped) – Piter _OS Jan 11 '16 at 05:50
  • you may be doing something wrong. Post a new question with details of some code. so other people can help you – Jeegar Patel Jan 11 '16 at 05:52