Creating a virtual serial device in linux programmatically

202 views Asked by At

I want to implement a modbus slave simulator that creates it's own serial device.

Something like in this example, where socat creates a "tunnel" between /dev/pts/6 and /dev/pts/7 and then diagslave will open one of them. The modbus client can then connect to the other one.

I've modified some code in https://github.com/simonvetter/modbus/tree/simon/refactor-rtu-transport, to be able to create a modbus server that can take RTU messages and it also works with socat.

But I want to overcome this step and create the /dev/pts/x directly.

So can it be done? Something like socat is doing? Ideally in go or c.

1

There are 1 answers

3
yoonghm On

Can you try if the following command could work? socat -d -d pty,raw,echo=0 pty,raw,echo=0

If so, Ctrl+C to terminate socat or exit the terminal. Use this template to do what you want:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

int main() {
    pid_t pid = fork();

    if (pid < 0) {
        // Handle error
        return 1;
    } else if (pid == 0) {
        // This is the child process
        char *args[] = {"socat", "-d", "-d", "pty,raw,echo=0", "pty,raw,echo=0", NULL};
        execvp(args[0], args);
        // If execvp returns, there was an error
        perror("execvp");
        return 1;
    } else {
        // This is the parent process
        // Put your code here

        // After all are done, sends a SIGTERM to kill the socat child process
        sleep(3);  // For example, wait 3 seconds
        kill(pid, SIGTERM);
        waitpid(pid, NULL, 0);  // Wait for the child process to exit
    }

    return 0;
}