Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should named pipes opened with mkfifo be closed and how?

I am using a named pipe to capture the output of an external program (wgrib2) within another program (MATLAB). The MATLAB code is below, and system() accesses the command line to make the pipe:

system('mkfifo myfifo');     % Make a named pipe myfifo
% Call the external program wgrib2 and dump its output to the named pipe myfifo
system('wgrib2.exe multi_1.glo_30m.hs.201212.grb2 -ij 1 165 -ij 1 166 > myfifo &');
fid = fopen('myfifo', 'r');  % Open the named pipe
a = fscanf(fid, '%c');       % Read the output as character
fclose(fid);                 % Close the "file" (myfifo still exists afterward)

Here are my questions:

  1. Do I have to close the named pipe myfifo after I use it? It seems to persist after the code is run.
  2. If myfifo needs to be closed, what is the command to close it?
  3. I will be running the code sample above many times (>1000), so is it OK if I reuse the named pipe and do not close it until the end?
like image 451
KAE Avatar asked Feb 01 '13 14:02

KAE


People also ask

How do you close a FIFO?

Closing a FIFOThe parent closes the FIFO after writing all the data. The child had previously opened the FIFO in READ ONLY mode (and no other processes have the FIFO open for WRITING).

What is the difference between pipe and named pipe?

A traditional pipe is “unnamed” and lasts only as long as the process. A named pipe, however, can last as long as the system is up, beyond the life of the process. It can be deleted if no longer used. Usually a named pipe appears as a file and generally processes attach to it for inter-process communication.

Are named pipes thread safe?

Yes, it is inherently thread safe, because it doesn't use a handle, a buffer, or anything else on the client side that the two (or more) threads might try to access simultaneously. Each time you call CallNamedPipe it opens a new instance of the named pipe, sends the message, and closes the handle.


1 Answers

  1. No. Unix treats everything like a file. Named pipes are not different. If you’re done using it, you probably want to close it so you don’t clutter up your machine with named pipes, but you don’t need to close it.

Edited to reflect below comment, which is correct. Deleting != closing.

  1. You close the named pipe the same way you close any file:
    fclose(mFifo)

As mentioned in the accepted answer, closing will not delete the fifo. You may need to do that separately.

  1. There’s nothing wrong with re-using a named pipe. It’s up to you, however, to know when you’re done reading/writing to it for each iteration. Once all the data has been read out of the pipe, you’re free to use it again as many times as you want.
like image 52
Jeffrey Portouw Avatar answered Sep 26 '22 03:09

Jeffrey Portouw