Say I have 2 processes, ProcessA and ProcessB. If I perform int fd=open(somefile)
in ProcessA, can I then pass the value of file descriptor fd
over IPC to ProcessB and have it manipulate the same file?
相关问题
- Multiple sockets for clients to connect to
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- how to get running process information in java?
You can use the method nos described in this thread, or the (more conventional) way, by sharing it between related processes (typically parent-child or siblings) by having it created, the forked processes automatically receive a copy.
Indeed, forked processes get all your FDs and can use them unless they close them (which is generally a good idea).
Therefore if a parent forks two children, if they both have a file descriptor they didn't close, it is now shared (even if the parent subsequently closes it). This could, for example, be a pipe from one child to another. This is how shell redirects like
Work.
If both processes belong the the same user, then you can simply make use of the procfs.
Of course you would need to some IPC mechanism to share the value of
SOURCE_FD
. See e.g. “Linux C: upon receiving a signal, is it possible to know the PID of the sender?”.Note that in the example of above, the setting of variables when receiving, like:
is not required. The whole idea of a message structure with headers is that the receiving site does not have to know what it reads, and can by checking the (first) header, what kind of message it is and what to expect.
You can pass a file descriptor to another process over unix domain sockets. Here's the code to pass such a file descriptor, taken from Unix Network Programming
And here's the code to receive the file descriptor