How can I share file descriptor across process using Android binder IPC in C++? Can you post example also?
File descriptors are generally unique to each process, but they can be shared by child processes created with a fork subroutine or copied by the fcntl, dup, and dup2 subroutines.
Binder is an Android-specific interprocess communication mechanism, and remote method invocation system. That is, one Android process can call a routine in another Android process, using binder to indentify the method to invoke and pass the arguments between processes.
Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes. The main practical use for a file descriptor is to create a FileInputStream or FileOutputStream to contain it.
Binder IPC Framework in Android Framework enables a remote invocation of the methods in other processes. A client process communicate to another server process and can run the methods in other process as it is done locally and can get the required data from the server process.
In client process we do the following to perform a binder transaction
remote()->transact(MYTRANSACTION, data, &reply, IBinder::FLAG_ONEWAY);
data and reply are of type Parcel. marshall and unmarshalling is done in native android using Parcel objects. It has the functionality to marshall a file descriptor.
data.writeFileDescriptor(fd);
In server process (i.e, Service in android), we call the following method to read the file descriptor in the server process.
int fd = data.readFileDescriptor();
sharing the file descriptor across process will be handled by the binder driver.
Important : duplicate the received file descriptor before the parcel object is destroyed.
You can find the implementation and explanation for native binder at Android-HelloWorldService
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With