我试图将指向ashmem区域的文件描述符从Service(进程A)传递给Activity(进程B)。在服务中我将原生文件描述符放入ParcelFileDescriptor并将其放入捆绑包中,然后通过Messenger发送。但是,当我尝试在Activity中使用此文件描述符mmap()时,我得到errno == 9(EBADF,错误的文件编号)。
在服务的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));
在活动的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
这里有什么问题?我甚至不确定传递文件描述符是否存在问题,我不知道还能检查什么。
答案 0 :(得分:2)
//我找不到带有ashmem_create_region **的库
它是cutils库的一部分。您可以将其添加到Android.mk文件中,如下所示:
LOCAL_LDLIBS := -lcutils
答案 1 :(得分:0)
没关系,它应该工作:)。我在代码中的某个地方得到了一些愚蠢的调试+9,它正确返回0。 我将代码留作参考。