aboutsummaryrefslogtreecommitdiff
path: root/slave.c
diff options
context:
space:
mode:
authorDaniel Eklöf <daniel@ekloef.se>2019-10-30 17:05:03 +0000
committerDaniel Eklöf <daniel@ekloef.se>2019-10-30 17:05:03 +0000
commit18921f7f45db38a9393992e4dd26a8046117a8a6 (patch)
treeaa8608d6e0a9b8268468c3b0ed1a4c399df9217f /slave.c
parentterm: break out font initialization to a separate function (diff)
term: move client startup to a new function, slave_spawn()
Diffstat (limited to 'slave.c')
-rw-r--r--slave.c72
1 files changed, 70 insertions, 2 deletions
diff --git a/slave.c b/slave.c
index 92571fde..df784a7f 100644
--- a/slave.c
+++ b/slave.c
@@ -1,9 +1,10 @@
#define _XOPEN_SOURCE 500
#include "slave.h"
#include <stdlib.h>
+#include <string.h>
#include <unistd.h>
#include <errno.h>
-#include <string.h>
+#include <assert.h>
#include <sys/stat.h>
#include <fcntl.h>
@@ -12,7 +13,9 @@
#define LOG_ENABLE_DBG 0
#include "log.h"
-void
+#include "tokenize.h"
+
+static void
slave_exec(int ptmx, char *const argv[], int err_fd)
{
int pts = -1;
@@ -62,3 +65,68 @@ err:
close(ptmx);
_exit(errno);
}
+
+pid_t
+slave_spawn(int ptmx, int argc, char *const *argv,
+ const char *conf_shell)
+{
+ int fork_pipe[2];
+ if (pipe2(fork_pipe, O_CLOEXEC) < 0) {
+ LOG_ERRNO("failed to create pipe");
+ return -1;
+ }
+
+ pid_t pid = fork();
+ switch (pid) {
+ case -1:
+ LOG_ERRNO("failed to fork");
+ close(fork_pipe[0]);
+ close(fork_pipe[1]);
+ return -1;
+
+ case 0:
+ /* Child */
+ close(fork_pipe[0]); /* Close read end */
+
+ char **_shell_argv = NULL;
+ char *const *shell_argv = argv;
+
+ if (argc == 0) {
+ char *shell_copy = strdup(conf_shell);
+ if (!tokenize_cmdline(shell_copy, &_shell_argv)) {
+ free(shell_copy);
+ (void)!write(fork_pipe[1], &errno, sizeof(errno));
+ _exit(0);
+ }
+ shell_argv = _shell_argv;
+ }
+
+ slave_exec(ptmx, shell_argv, fork_pipe[1]);
+ assert(false);
+ break;
+
+ default: {
+ close(fork_pipe[1]); /* Close write end */
+ LOG_DBG("slave has PID %d", term->slave);
+
+ int _errno;
+ static_assert(sizeof(errno) == sizeof(_errno), "errno size mismatch");
+
+ ssize_t ret = read(fork_pipe[0], &_errno, sizeof(_errno));
+ close(fork_pipe[0]);
+
+ if (ret < 0) {
+ LOG_ERRNO("failed to read from pipe");
+ return -1;
+ } else if (ret == sizeof(_errno)) {
+ LOG_ERRNO(
+ "%s: failed to execute", argc == 0 ? conf_shell : argv[0]);
+ return -1;
+ } else
+ LOG_DBG("%s: successfully started", conf->shell);
+ break;
+ }
+ }
+
+ return pid;
+}