Skip to content

June 8, 2017

pthread_cancel and blocking I/O in Android NDK

by Joe Kuan

We have a multi-threaded program that has one thread sitting in a while loop blocking from recvfrom system call on a socket. I need to run this C program on mobile. Unfortunately, in the networking side of mobile development, IP address changes all the time and the socket descriptor becomes invalid. Hence we need to break the loop and reconnect the socket.

First approach is to destroy the thread the recreate it again when IP address is changed. So the thread can go through closing the old socket gracefully, creates a new socket with the new IP address and enters the while loop of receiving packets. Quick and simple. However, if you are porting a multi-threaded C/C++ program for Android, perhaps this may not be a smooth ride. This is because pthread_cancel is not available in the Android NDK. So we can’t kill the thread and we need a way to signal blocking I/O recvfrom call.

Second approach is to close the socket descriptor and the recvfrom should return with error. However, this doesn’t happen in Android. The recvfrom continues to block.

Third approach is to set non-blocking I/O option in socket and handles the errno returning from recvfrom.

struct time tv;
tv.tv_sec = 1;
setsockopt(socketfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));

Another surprise in Android, it won’t let you do that.

I am running out of magic 8-ball. Luckily, the shutdown system call on socket lets you terminate the blocking I/O.

At the time of writing, I’m using API level 24.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: