英文:
Creating a virtual serial device in linux programmatically
问题
我想实现一个Modbus从设备模拟器,它可以创建自己的串行设备。
就像这个示例中的情况一样,socat在/dev/pts/6和/dev/pts/7之间创建了一个“隧道”,然后diagslave将打开其中一个。Modbus客户端可以连接到另一个设备。
我已经修改了https://github.com/simonvetter/modbus/tree/simon/refactor-rtu-transport中的一些代码,以便创建一个可以接收RTU消息并且可以与socat一起使用的Modbus服务器。
但是我想跳过这一步,直接创建/dev/pts/x。这样可以实现吗?类似于socat的方式?最好使用go或c语言实现。
英文:
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
得分: 1
你能尝试一下下面的命令吗?看看是否能正常工作?
socat -d -d pty,raw,echo=0 pty,raw,echo=0
如果可以的话,使用Ctrl+C终止socat或退出终端。使用这个模板来实现你想要的功能:
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
int main() {
    pid_t pid = fork();
    if (pid < 0) {
        // 处理错误
        return 1;
    } else if (pid == 0) {
        // 这是子进程
        char *args[] = {"socat", "-d", "-d", "pty,raw,echo=0", "pty,raw,echo=0", NULL};
        execvp(args[0], args);
        // 如果execvp返回,说明有错误发生
        perror("execvp");
        return 1;
    } else {
        // 这是父进程
        // 在这里放置你的代码
        // 完成所有操作后,发送SIGTERM信号终止socat子进程
        sleep(3);  // 例如,等待3秒钟
        kill(pid, SIGTERM);
        waitpid(pid, NULL, 0);  // 等待子进程退出
    }
    return 0;
}
英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论