Claudia Ramos Claudia Ramos - 2 months ago 16
Android Question

Read/Write bytes within two processes (apps) using virtual serial communication on Android

I have written a C/C++ application (NDK) for Android which can open a virtual port for serial communication. It writes and reads bytes from the port within the same process. This is so far working and I didn´t have to root my device in order to do this. It is a simple programm which does the following:

int fd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
if (fd == -1) {
LOGW("error opening file");

return 1;
}

grantpt(fd);
unlockpt(fd);

char* pts_name = ptsname(fd);
LOGI("ptsname: %s\n", pts_name);

char* inputbyte = "This is a test\n";

char byte;

int numOfBytesWritten = write(fd, inputbyte, strlen(inputbyte));
LOGI("Number of bytes written: %d\n", numOfBytesWritten);

while (read(fd, &byte, 1) == 1) {
LOGI("Byte: %c\n", byte);
}

close(fd);


Now the problem is that if I want to do this same thing within two processes (two apps) it doesn´t work. One process opens /dev/ptmx, and the other process should open the /dev/pts directory. Everytime the slave tries to open the /dev/pts directory I get the error "error opening file" (-1). I have rooted my device and this is still not working. I have a sleep function after opening the /dev/ptmx directory in order to wait for the slave.

What should I do? Any ideas?

Answer

I have solved the problem so I will post the solution in case someone else is interested:

(1) Your phone should be rooted.

(2) The master opens a port in the form "/dev/pts/N" (variable pts_name in this example) where N is a number. This port is given by:

int fd = open("/dev/ptmx", O_RDWR | O_NOCTTY);  
if (fd == -1) {
     LOGW("error opening file");
     return 1;  
}  
char* pts_name = ptsname(fd);  
LOGI("ptsname: %s\n", pts_name);

(3) Give permissions to the port (this can be done programmatically or from the adb shell). From the shell would be:

  • su
  • chmod 666 pts_name (for example chmod 666 /dev/pts/4).

(4) Execute the slave which opens exactly this port. For example int fd = open("/dev/pts/4", O_RDWR);

(5) Voilà!