Reputation: 18875
When using the open() function in C, I get a fd (file descriptor). I was wondering if it's the same thing as its process id, because as I know, fd is an integer.
Upvotes: 3
Views: 3644
Reputation: 1346
No...
A file descriptor is an opaque handle that is used in the interface between user space and the kernel to identify file/socket resources. Therefore when you use open()
or socket()
(system calls to interface to the kernel) you are returned a file descriptor, which is an integer (it is actually an index into the processes u structure - but that is not important). Therefore if you want to interface directly with the kernel, using system calls to read()
, write()
, close()
etc. the handle you use is a file descriptor.
A PID (i.e., process identification number) is an identification number that is automatically assigned to each process when it is created on a Unix-like operating system.A process is an executing (i.e., running) instance of a program. Each process is guaranteed a unique PID, which is always a non-negative integer.
One of the first things a UNIX programmer learns is that every running program starts with three files already opened:
Descriptive Name.............fd number...................... Description
Standard In 0 Input from the keyboard
Standard Out 1 Output to the console
Standard Error 2 Error output to the console
If you create any file descriptor, mostly you will get value as 3. Because 3 is least available +ve integer to allocate for fd. Because STDIN
,STDOUT
,STDERR
are occupied with 0,1,2 respectively. That is why fd is called as smallest non negative integer.
Upvotes: 4
Reputation: 758
No it is not.
PID is process identifier, and file descriptor is file handler identifier.
Specifically from Wikipedia about File Descriptors:
(...) file descriptor (FD) is an abstract indicator for accessing a file. The term is generally used in POSIX operating systems.
In POSIX, a file descriptor is an integer, specifically of the C type int. (...)
And for PID:
[PID] is a number used by most operating system kernels, — such as that of UNIX, Mac OS X or Microsoft Windows — to temporarily uniquely identify a process (...)
Upvotes: 8
Reputation: 23332
No, file descriptors are indices into the file table of your own process. They are always small integers (that is, up to the max-open-files limit for the process) because, among other things, the bitmap interface to select() wouldn't work if they were arbitrary numbers. On the other hand PIDs typically grow to at least 32767 before the wrap around.
An open file in general doesn't have a process ID of its own. And even in the case where one might arguably expect it to be connected to a particular process -- namely when the file handle comes from popen() -- there's no such direct connection and what goes on inside popen() is more complex than "treat this process as if it was a file".
Upvotes: 5