title: Send Java FD via UNIX Domain sockets using JNI
body: <p>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.</p>
  
  <p>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 <strong>fdToSend</strong>. </p>
  
  <p>When my JNI code attempts to call sendmsg(), an error occurs stating "Bad file number".</p>
  
  <p>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. </p>
  
  <p>The sendfd() method is exactly as found in [2].</p>
  
  <p>Below is my bridging JNI function:</p>
  
  <pre><code>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(&amp;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*)&amp;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);
  }
  </code></pre>
  
  <p>[1] <a href="http://developer.android.com/reference/android/os/ParcelFileDescriptor.html#getFd()" rel="nofollow noreferrer">http://developer.android.com/reference/android/os/ParcelFileDescriptor.html#getFd()</a></p>
  
  <p>[2] <a href="https://stackoverflow.com/a/4491203/2796346">https://stackoverflow.com/a/4491203/2796346</a></p>