I am writting an application for Android which passes a JAVA fd taken from ParcelFileDescriptor.getFd() which according to [1] states that the int I get back is a native fd.
Now, with this fd, I am trying to write it over a unix domain socket to the existing process which is listening. To do this, I am using JNI and I pass the int received above to the JNI function as an argument named fdToSend.
When my JNI code attempts to call sendmsg(), an error occurs stating "Bad file number".
With some help from google, It seems like the socket connection might be closed when I call sendmsg(), but I cannot see how this would be the case.
The sendfd() method is exactly as found in [2].
Below is my bridging JNI function:
JNIEXPORT jint JNICALL Java_com_example_myapp_AppManager_bridgeSendFd(JNIEnv *env, jint fdToSend) {
int fd;
struct sockaddr_un addr;
if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
__android_log_print(ANDROID_LOG_ERROR, APPNAME, "socket() failed: %s (socket fd = %d)\n", strerror(errno), fd);
return (jint)-1;
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, "/data/data/com.example.myapp/sock_path", sizeof(addr.sun_path)-1);
if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
__android_log_print(ANDROID_LOG_ERROR, APPNAME, "connect() failed: %s (fd = %d)\n", strerror(errno), fd);
return (jint)-1;
}
return (jint)sendfd(fd, (int)fdToSend);
}
[1] http://developer.android.com/reference/android/os/ParcelFileDescriptor.html#getFd()