lib: Added variants of sendfd and sendreq that take sendmsg flags.
[ashd.git] / lib / proc.c
index 957cfce..a1dc336 100644 (file)
@@ -22,6 +22,7 @@
 #include <sys/socket.h>
 #include <errno.h>
 #include <ctype.h>
+#include <fcntl.h>
 
 #ifdef HAVE_CONFIG_H
 #include <config.h>
@@ -31,9 +32,8 @@
 #include <proc.h>
 #include <req.h>
 
-int stdmkchild(char **argv)
+int stdmkchild(char **argv, void (*chinit)(void *), void *idata)
 {
-    int i;
     pid_t pid;
     int fd[2];
     
@@ -42,21 +42,21 @@ int stdmkchild(char **argv)
     if((pid = fork()) < 0)
        return(-1);
     if(pid == 0) {
-       for(i = 3; i < FD_SETSIZE; i++) {
-           if(i != fd[0])
-               close(i);
-       }
+       if(chinit != NULL)
+           chinit(idata);
        dup2(fd[0], 0);
        close(fd[0]);
+       close(fd[1]);
        execvp(argv[0], argv);
        flog(LOG_WARNING, "could not exec child program %s: %s", argv[0], strerror(errno));
        exit(127);
     }
     close(fd[0]);
+    fcntl(fd[1], F_SETFD, FD_CLOEXEC);
     return(fd[1]);
 }
 
-int sendfd(int sock, int fd, char *data, size_t datalen)
+int sendfd2(int sock, int fd, char *data, size_t datalen, int flags)
 {
     struct msghdr msg;
     struct cmsghdr *cmsg;
@@ -78,13 +78,18 @@ int sendfd(int sock, int fd, char *data, size_t datalen)
     *((int *)CMSG_DATA(cmsg)) = fd;
     msg.msg_controllen = cmsg->cmsg_len;
     
-    return(sendmsg(sock, &msg, MSG_NOSIGNAL | MSG_DONTWAIT));
+    return(sendmsg(sock, &msg, flags));
+}
+
+int sendfd(int sock, int fd, char *data, size_t datalen)
+{
+    return(sendfd2(sock, fd, data, datalen, MSG_NOSIGNAL | MSG_DONTWAIT));
 }
 
 int recvfd(int sock, char **data, size_t *datalen)
 {
     int ret, fd;
-    char *buf, cbuf[1024];;
+    char *buf, cbuf[1024];
     struct msghdr msg;
     struct cmsghdr *cmsg;
     struct iovec bufvec;
@@ -124,7 +129,7 @@ int recvfd(int sock, char **data, size_t *datalen)
     return(fd);
 }
 
-pid_t stdforkserve(char **argv, struct hthead *req, int fd)
+pid_t stdforkserve(char **argv, struct hthead *req, int fd, void (*chinit)(void *), void *idata)
 {
     int i;
     char *ebuf, *p;
@@ -134,10 +139,12 @@ pid_t stdforkserve(char **argv, struct hthead *req, int fd)
     if((pid = fork()) < 0)
        return(-1);
     if(pid == 0) {
+       if(chinit != NULL)
+           chinit(idata);
+       
        dup2(fd, 0);
        dup2(fd, 1);
-       for(i = 3; i < FD_SETSIZE; i++)
-           close(i);
+       close(fd);
        
        bufinit(args);
        for(i = 0; argv[i]; i++)
@@ -163,6 +170,5 @@ pid_t stdforkserve(char **argv, struct hthead *req, int fd)
        flog(LOG_WARNING, "could not exec child program %s: %s", argv[0], strerror(errno));
        exit(127);
     }
-    close(fd);
     return(pid);
 }