The file descriptor 1 translates to the stdout FILE structure in the Kernel's Open Files Table.
This is a misunderstanding. The kernel's file table has nothing whatsoever to do with user-space file structures.
In any event, the kernel has two levels of indirection. There is the internal structure that represents the file itself, which is reference counted. There is an "open file description" that is reference counted. And then there is the file handle, which is not reference counted. The file structure points the way to the inode itself. The open file description contains things like the open mode and file pointer.
When you call close, you always close the file handle. When a file handle is closed, the reference count on its open file description is decremented. If it goes to zero, the open file description is also released and the reference count on the file itself is decremented. Only if that goes to zero is the kernel's file structure freed.
There is no chance for one process to release a resource another process is using because shared resources are reference counted.
A fork
is really a fork. You obtain two almost identical processes. The main difference is the returned value of the fork()
system call which is the pid of the child in the one that is identified as parent and 0 in the child (which is how the software can determine which process is considered the parent (the parent has the responsibility to take care of its children) and which is the child).
In particular, the memory is duplicated, so the fd
array will contain the same thing (if fd[0]
is 3 in one process, it will be 3 as well in the other) and the file descriptors are duplicated. fd 3 in the child will point to the same open file description as fd 3 in the parent.
So fd 3 of both parent and child will point to one end of the pipe, and fd 4 (fd[1]
) of both parent and child will point to the other end.
You want to use that pipe for one process to send data to the other one. Typically one of the processes will write to fd 4 and the other one will read from fd 3 until it sees end of file.
end of file is reached when all the fds open to the other side of the pipe have been closed. So if the reader doesn't close its fd to the other side, it will never see the end of file.
Similarly if the reader dies, the writer will never know that it must stop writing if it hasn't closed its own fd to the other side of the pipe.
Best Answer
Yes, the file will be automatically closed when the process terminates, regardless of the reason for the process termination.
This is documented in POSIX. In “Consequences of Process Termination”, among other consequences:
And in “Terminating a Process”: