inittab: use more robust dev_exist() implementation
[project/procd.git] / inittab.c
index f8f0218..528396e 100644 (file)
--- a/inittab.c
+++ b/inittab.c
@@ -65,50 +65,35 @@ static char *ask = "/sbin/askfirst";
 
 static LIST_HEAD(actions);
 
-static int dev_open(const char *dev)
+static int dev_exist(const char *dev)
 {
-       int fd = -1;
-
-       if (dev) {
-               if (chdir("/dev"))
-                       ERROR("failed to change dir to /dev\n");
-               fd = open(dev, O_RDWR);
-               if (chdir("/"))
-                       ERROR("failed to change dir to /\n");
-       }
+       int dfd, fd;
 
-       return fd;
-}
+       dfd = open("/dev", O_PATH|O_DIRECTORY);
 
-static int dev_exist(const char *dev)
-{
-       int res;
+       if (dfd < 0)
+               return 0;
+
+       fd = openat(dfd, dev, O_RDONLY);
+       close(dfd);
 
-       res = dev_open(dev);
-       if (res != -1)
-               close(res);
+       if (fd < 0)
+               return 0;
 
-       return (res != -1);
+       close(fd);
+       return 1;
 }
 
 static void fork_worker(struct init_action *a)
 {
-       int fd;
        pid_t p;
 
        a->proc.pid = fork();
        if (!a->proc.pid) {
                p = setsid();
 
-               fd = dev_open(a->id);
-               if (fd != -1)
-               {
-                       dup2(fd, STDIN_FILENO);
-                       dup2(fd, STDOUT_FILENO);
-                       dup2(fd, STDERR_FILENO);
-                       if (fd > STDERR_FILENO)
-                               close(fd);
-               }
+               if (patch_stdio(a->id))
+                       ERROR("Failed to setup i/o redirection\n");
 
                ioctl(STDIN_FILENO, TIOCSCTTY, 1);
                tcsetpgrp(STDIN_FILENO, p);