Micheal.zu
Micheal.zu

Reputation: 85

recvmsg return error(EBADF) when communicate between two processes using socketpair?

I'm developing a program which do IPC's call between two processes.I create two socket fd using socketpair:

int fds[2] = {-1,-1};
if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds)) {
    return NULL;
}

In process A(with system permission), I send an integer(handle) by send (using fd[0]) function:

int sock_send_all(int sock_fd, const uint8_t* buf, int len) {  
    int s = len;
    int ret = send(sock_fd, buf, s, 0);
    ...
}  

In Process B(with user permission), it wait to receive the handle by recvmsg (using fd[1]):

ret = recvmsg(fd, &msg, MSG_NOSIGNAL);  

problem occurs in here: the recvmsg immediately return -1 with errorno equals 9(EBADF)!

I have surfed web a long time to try to find the answer but no any helpful information. Do you have any hints or suggestions? Thanks!

Is this an issue about process privilege level? or I should use setsockopt to set something?

Upvotes: 0

Views: 708

Answers (2)

Micheal.zu
Micheal.zu

Reputation: 85

I have resolved my problem.
The key point is to encapsulate the raw file descriptor into ParcelFileDescriptor object and transfer the object to another process, rather than transfer the file descriptor directly between two processes.
I think the implementation of ParcelFileDescriptor in android does some configurations about the raw file descriptor. Maybe I should read the implementation code to find the real reason of that. Thanks all of u!

Upvotes: 1

user207421
user207421

Reputation: 311018

Unless there is something about IBinder that I don't know, handles in one process aren't valid in another process. Why can't you keep using the original socket?

Upvotes: 0

Related Questions