I am using the VpnService to create a tunnel interface. The interface gets created correctly. I am able to set the routes and MTU on the tunnel interface as well. However, when I perform a read on this interface the read never blocks leading to a busy wait and wasted CPU cycles.
This is the run loop of my code to read from the tunnel interface:` public synchronized void run() { Log.v(TAG, "Launching the stitch tunnel thread");
FileInputStream in = new FileInputStream(_tunnel_interface.getFileDescriptor());
byte[] pktBuf = new byte[1024];
while(true) {
try {
int length = in.read(pktBuf);
Log.v(TAG, "Got a packet of length"+Integer.toString(length));
if ( length == 0) {
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
Log.w(TAG, "Thread was interrupted:"+e.toString());
stopSelf();
return;
}
}
} catch (IOException e) {
Log.w(TAG, "Stitch tunnel interface close unexpectedly:"+ e.toString());
stopSelf();
return;
}
}
}`
I checked the ToyVPN example and seems like even there the code doesn't expect to block on calling read on the tunnel interface.
Is this a bug? According to JAVA specifications for read on a fileinputstream, the read call should return 0 bytes only if the buffer that is passed is of length zero. This is obviously not the case over here. So a bit confused with the behavior I am observing.
From the VpnService.Builder establish
method documentation :
"The file descriptor is put into non-blocking mode by default to avoid blocking Java threads."
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.