Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-open a closed file descriptor

Tags:

c

pipe

I have a scenario where i created pipe for communication between two child and parent. Parent writes (using write function)data to the pipe and closes the respective file descriptor. The problem is when i want to write data again to the pipe, the write function is returning error code -1. I think its because writing end has been closed in previous iteration. Then how to open the corresponding file descriptor after it has been closed once.

I tried using open() function which requires path to some file as arguement. But i am not using any files in my application. I have simple file descriptors (int arr[2]).

Is it possible to achieve above scenario with pipes????

like image 394
chaitu Avatar asked Mar 30 '12 05:03

chaitu


People also ask

How do I reopen a file descriptor?

File descriptors may be directly accessed using bash, the default shell of Linux, macOS X, and Windows Subsystem for Linux.

What happens when a file descriptor is closed?

close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).

Can you reopen a closed pipe?

Once a pipe is closed, it's closed. You can't bring it back. If you want to write more to it, don't close it in the first place - it's as simple as that.

How do I open a closed file?

To recover and reopen an accidentally closed window, right-click on the icon and select the file you wish to reopen. To recover all, simply double-click on the icon. Features: Click the X or press Alt-F4 to close an application.


2 Answers

Once a pipe is closed, it's closed. You can't bring it back.

If you want to write more to it, don't close it in the first place - it's as simple as that.

like image 119
caf Avatar answered Sep 25 '22 22:09

caf


Thing to know about anything related to files (pipes are also some sort of files) under unix: file name is used only on opening file. Later until file is open, it is available forever until closed and name is never used again. When someone deletes file in another window while it is open, just name is gone, not file. This means:

  1. File is still on disk
  2. It has no name
  3. It is still open
  4. When it is closed, kernel removes it forever

Knowing this maybe helps to understand, why this would be nearly impossible to "reopen" file, pipe or anything similar again. File name and descriptor have different lifetimes.

The only exceptions are stdout and stderr whose descriptor are always known as 1 and 2.

like image 26
Tõnu Samuel Avatar answered Sep 23 '22 22:09

Tõnu Samuel