我正在尝试将指向ashmem区域的文件描述符从Service(进程A)传递到Activity(进程B)。在Service中,我将本机文件描述符放入ParcelFileDescriptor并将其放入捆绑包中,然后通过Messenger发送。但是,当我尝试在Activity中使用此文件描述符进行mmap()时,得到errno == 9(EBADF,错误的文件号)。
在Service的JNI中创建ashmem区域:
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;
}
将fd从服务发送到活动:
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();
}
在活动中接收fd:
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));
在Activity的JNI中处理fd:
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;
}
这是我在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
怎么了 我什至不确定传递文件描述符是否有问题,我不知道还能检查什么。
没关系,它可以正常工作:)。我在代码中某处有一些愚蠢的调试+9,它正确地返回0。我将代码留作参考。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句