Skip to content

Commit

Permalink
terminal: set the pty fd non blocking
Browse files Browse the repository at this point in the history
  • Loading branch information
tsl0922 committed Dec 5, 2019
1 parent ca91f40 commit cfd338e
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 4 deletions.
4 changes: 4 additions & 0 deletions src/protocol.c
Expand Up @@ -175,6 +175,10 @@ spawn_process(struct pss_tty *pss) {

uv_signal_start(&pss->watcher, child_cb, SIGCHLD);

// ensure the lws socket fd close-on-exec
fd_set_cloexec(lws_get_socket_fd(pss->wsi));

// create process with pseudo-tty
pss->pid = pty_fork(&pss->pty, argv[0], argv, server->terminal_type);
if (pss->pid < 0) {
lwsl_err("pty_fork: %d (%s)\n", errno, strerror(errno));
Expand Down
12 changes: 8 additions & 4 deletions src/terminal.c
Expand Up @@ -14,6 +14,8 @@
#include <pty.h>
#endif

#include "utils.h"

pid_t
pty_fork(int *pty, const char *file, char *const argv[], const char *term) {
pid_t pid = forkpty(pty, NULL, NULL, NULL);
Expand All @@ -29,11 +31,13 @@ pty_fork(int *pty, const char *file, char *const argv[], const char *term) {
}
}

// set the file descriptor close-on-exec
int status_flags = fcntl(*pty, F_GETFL);
if (status_flags != -1) {
fcntl(*pty, F_SETFD, status_flags | FD_CLOEXEC);
// set the file descriptor non blocking
int flags = fcntl(*pty, F_GETFL);
if (flags != -1) {
fcntl(*pty, F_SETFD, flags | O_NONBLOCK);
}
// set the file descriptor close-on-exec
fd_set_cloexec(*pty);

return pid;
}
Expand Down
9 changes: 9 additions & 0 deletions src/utils.c
Expand Up @@ -5,6 +5,7 @@
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>

#ifdef __linux__
Expand Down Expand Up @@ -85,6 +86,14 @@ get_sig(const char *sig_name) {
return atoi(sig_name);
}

bool
fd_set_cloexec(const int fd) {
int flags = fcntl(fd, F_GETFD);
if (flags < 0)
return false;
return (flags & FD_CLOEXEC) == 0 || fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1;
}

int
wait_proc(pid_t in, pid_t *out) {
int stat = 0, pid;
Expand Down
4 changes: 4 additions & 0 deletions src/utils.h
Expand Up @@ -25,6 +25,10 @@ get_sig_name(int sig, char *buf, size_t len);
int
get_sig(const char *sig_name);

// Set the given file descriptor close-on-exec
bool
fd_set_cloexec(const int fd);

// waitpid with WNOHANG and return the status
int
wait_proc(pid_t in, pid_t *out);
Expand Down

0 comments on commit cfd338e

Please sign in to comment.