I'm trying to pass file descriptor pointing to a ashmem region from Service (process A) to Activity (process B). In Service I'm puting the native file descriptor to ParcelFileDescriptor and that into a bundle, and I send that via Messenger. However when I try to mmap() using this file descriptor in Activity, I get errno == 9 (EBADF, bad file number).
Creating ashmem region in Service's JNI:
int fd;
int *buff;
JNIEXPORT jint JNICALL Java_com_example_testservice_Test_getTestFD
/* int Test.getTestFD() */
(JNIEnv * env, jclass jthis) {
fd = open("/dev/ashmem", O_RDWR); // I couldn't find library with ashmem_create_region
ioctl(fd, ASHMEM_SET_NAME, "my_mem");
ioctl(fd, ASHMEM_SET_SIZE, 640*480*12);
buff = mmap(NULL, 640*480*12, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(buff == MAP_FAILED)
return -1;
buff[0] = 4;
buff[1] = 5;
buff[2] = 6;
return fd;
}
Sending fd from Service to Activity:
int nFD = Test.getTestFD();
ParcelFileDescriptor fd;
try {
fd = ParcelFileDescriptor.fromFd(nFD);
Message reply = Message.obtain(this, msg.what, nFD, 0);
Bundle b = new Bundle(1);
b.putParcelable("fd", fd);
reply.setData(b);
if(msg.replyTo == null) { // Activity asks for FD and we reply to it's message
Log.e("TestService", "Missing replyTo");
} else {
try {
msg.replyTo.send(reply);
} catch (RemoteException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
Receiving fd in Activity:
Bundle bundle = msg.getData();
ParcelFileDescriptor fd = bundle.getParcelable("fd");
int nFD = fd.getFd();
Log.d("ClientLib", "Received FD (Parcel): "+String.valueOf(nFD));
Log.d("ClientLib", "Received FD (raw): "+String.valueOf(msg.arg1));
int ret = Interface.SetDataFD(nFD); // implementation below
if(ret != 0)
Log.e("ClientLib", "SetDataFD (parcel) failed. Error code: "+String.valueOf(ret));
ret = Interface.SetDataFD(msg.arg1);
if(ret != 0)
Log.e("ClientLib", "SetDataFD (raw) failed. Error code: "+String.valueOf(ret));
Handling fd in Activity's JNI :
int data_fd = -1;
JNIEXPORT
jint JNICALL Java_com_example_clientlib_Interface_SetDataFD
/* int SetDataFD(int fd) */
(JNIEnv * env, jclass jthis, jint fd)
{
data_fd = fd;
int * blah = (int*)mmap(NULL, 16, PROT_READ, MAP_SHARED, data_fd, 0);
if(blah == MAP_FAILED)
return errno;
return 0;
}
Here's what I get in logcat:
D/ClientLib(22104): Received FD (Parcel): 53
D/ClientLib(22104): Received FD (raw): 49
E/ClientLib(22104): SetDataFD (parcel) failed. Error code: 9
E/ClientLib(22104): SetDataFD (raw) failed. Error code: 19
What's wrong here? I'm not even sure if that's a problem with passing file descriptor, I don't know what else I can check.
Nevermind, it works as it should :). I've got some stupid debugish +9 somewhere in the code, it was properly returning 0. I'm leaving the code for reference.