r/C_Programming • u/Senior-Question693 • 5d ago
forkpty error
i'm trying to make a terminal emulator but i can't figure out how to open a pty.
when i try to open a pty bouth forkpty from pty.h and my own implementation:
int init_pty() {
int ptymaster_fd = posix_openpt(O_RDWR);
if (ptymaster_fd == -1) {
perror("failed to open pty master");
close(ptymaster_fd);
return 1;
}
if (grantpt(ptymaster_fd) == -1) {
perror("failed to grantpt");
close(ptymaster_fd);
return 1;
}
if (unlockpt(ptymaster_fd) == -1) {
perror("failed to unlockpt");
close(ptymaster_fd);
return 1;
}
char* ptyslave_name = ptsname(ptymaster_fd);
if (ptyslave_name == NULL) {
perror("failed to get pty slave name");
close(ptymaster_fd);
return 1;
}
pid_t pid = fork();
if (pid != 0) {
perror("fork");
close(ptymaster_fd);
return 1;
}
setsid();
int ptyslave_fd = open(ptyslave_name, O_RDWR);
if (ptyslave_fd == -1) {
perror("failed to open pty slave");
return 1;
}
ioctl(ptyslave_fd, TIOCSCTTY, 0);
dup2(ptyslave_fd, STDIN_FILENO);
dup2(ptyslave_fd, STDOUT_FILENO);
dup2(ptyslave_fd, STDERR_FILENO);
return ptymaster_fd;
}
fail when forking with the error directory not empty, ai says that it fails because /dev/pts is not empty but it's obviously trippin balls as usual =), so why does it fail then (?_?)
6
Upvotes
2
u/Playa_Sin_Nombre 5d ago edited 5d ago
I don't know how terminal emulators or forkpty work, but
pid != 0does not necessarily imply afork()error.fork()returns-1on error, but on success it returns a positive integer in the parent process. This value is the actual PID of the child. That means your parent process is entering that if block, callingperror(), and immediately returning 1.But if
fork()didn't fail, thenfork()is not settingerrno. Therefore thatperror()call is using whatever the current value oferrnois at that moment, which is undefined.See the following:
From: https://www.man7.org/linux/man-pages/man3/perror.3.html