I'm currently trying to manually feed data into GPSD. To do this I have a script that currently outputs the data (its just a JSON string) to stdout, then use socat to make a sort of fake serial device. However, I don't want to use another process, so essentially I want to integrate the creation, linking, and continuous writing to a pty from that c code. Here's what I currently have, its just some test code to write a string to pty. But when I cat into the device while its running nothing shows up.'
#include <sys/stat.h>
#include <fcntl.h>
#define _XOPEN_SOURCE 600
#include <termios.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#define MAX_SNAME 1000
int posix_openpt(int flags){
return open("/dev/ptmx", flags);
}
int ptyMasterOpen(char *slaveName, size_t snLen){
int masterFd, savedErrno;
char *p;
masterFd = posix_openpt(O_RDWR | O_NOCTTY); /* Open pty master */
if (masterFd == -1)
return -1;
if (grantpt(masterFd) == -1) { /* Grant access to slave pty */
savedErrno = errno;
close(masterFd); /* Might change 'errno' */
errno = savedErrno;
return -1;
}
if (unlockpt(masterFd) == -1) { /* Unlock slave pty */
savedErrno = errno;
close(masterFd); /* Might change 'errno' */
errno = savedErrno;
return -1;
}
p = ptsname(masterFd); /* Get slave pty name */
if (p == NULL) {
savedErrno = errno;
close(masterFd); /* Might change 'errno' */
errno = savedErrno;
return -1;
}
if (strlen(p) < snLen) {
strncpy(slaveName, p, snLen);
} else { /* Return an error if buffer too small */
close(masterFd);
errno = EOVERFLOW;
return -1;
}
return masterFd;
}
int main(int argc, char **argv) {
int flags = O_RDWR | O_NOCTTY | O_NDELAY;
char slavename[MAX_SNAME];
ptyMasterOpen(slavename, 900);
printf("%s", slavename);
int fd = open(slavename,flags);
char msg[] = "hello there......General Kenobi
";
for(;;){
write(fd, msg, sizeof(msg));
}
close(fd);
}
question from:
https://stackoverflow.com/questions/65924465/send-string-from-c-to-psuedo-terminal-to-mimic-serial-device 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…