Home | History | Annotate | Line # | Download | only in gen
popen.c revision 1.30
      1 /*	$NetBSD: popen.c,v 1.30 2010/11/14 18:11:42 tron Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software written by Ken Arnold and
      8  * published in UNIX Review, Vol. 6, No. 8.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #if defined(LIBC_SCCS) && !defined(lint)
     37 #if 0
     38 static char sccsid[] = "@(#)popen.c	8.3 (Berkeley) 5/3/95";
     39 #else
     40 __RCSID("$NetBSD: popen.c,v 1.30 2010/11/14 18:11:42 tron Exp $");
     41 #endif
     42 #endif /* LIBC_SCCS and not lint */
     43 
     44 #include "namespace.h"
     45 #include <sys/param.h>
     46 #include <sys/wait.h>
     47 #include <sys/socket.h>
     48 
     49 #include <assert.h>
     50 #include <errno.h>
     51 #include <paths.h>
     52 #include <signal.h>
     53 #include <stdio.h>
     54 #include <stdlib.h>
     55 #include <string.h>
     56 #include <unistd.h>
     57 
     58 #include "env.h"
     59 #include "reentrant.h"
     60 
     61 #ifdef __weak_alias
     62 __weak_alias(popen,_popen)
     63 __weak_alias(pclose,_pclose)
     64 #endif
     65 
     66 static struct pid {
     67 	struct pid *next;
     68 	FILE *fp;
     69 #ifdef _REENTRANT
     70 	int fd;
     71 #endif
     72 	pid_t pid;
     73 } *pidlist;
     74 
     75 #ifdef _REENTRANT
     76 static rwlock_t pidlist_lock = RWLOCK_INITIALIZER;
     77 #endif
     78 
     79 FILE *
     80 popen(const char *command, const char *type)
     81 {
     82 	struct pid *cur, *old;
     83 	FILE *iop;
     84 	const char * volatile xtype = type;
     85 	int pdes[2], pid, serrno;
     86 	volatile int twoway;
     87 
     88 	_DIAGASSERT(command != NULL);
     89 	_DIAGASSERT(xtype != NULL);
     90 
     91 	if (strchr(xtype, '+')) {
     92 		twoway = 1;
     93 		type = "r+";
     94 		if (socketpair(AF_LOCAL, SOCK_STREAM, 0, pdes) < 0)
     95 			return (NULL);
     96 	} else  {
     97 		twoway = 0;
     98 		if ((*xtype != 'r' && *xtype != 'w') || xtype[1] ||
     99 		    (pipe(pdes) < 0)) {
    100 			errno = EINVAL;
    101 			return (NULL);
    102 		}
    103 	}
    104 
    105 	if ((cur = malloc(sizeof(struct pid))) == NULL) {
    106 		(void)close(pdes[0]);
    107 		(void)close(pdes[1]);
    108 		errno = ENOMEM;
    109 		return (NULL);
    110 	}
    111 
    112 	(void)rwlock_rdlock(&pidlist_lock);
    113 	(void)__readlockenv();
    114 	switch (pid = vfork()) {
    115 	case -1:			/* Error. */
    116 		serrno = errno;
    117 		(void)__unlockenv();
    118 		(void)rwlock_unlock(&pidlist_lock);
    119 		free(cur);
    120 		(void)close(pdes[0]);
    121 		(void)close(pdes[1]);
    122 		errno = serrno;
    123 		return (NULL);
    124 		/* NOTREACHED */
    125 	case 0:				/* Child. */
    126 		/* POSIX.2 B.3.2.2 "popen() shall ensure that any streams
    127 		   from previous popen() calls that remain open in the
    128 		   parent process are closed in the new child process. */
    129 		for (old = pidlist; old; old = old->next)
    130 #ifdef _REENTRANT
    131 			close(old->fd); /* don't allow a flush */
    132 #else
    133 			close(fileno(old->fp)); /* don't allow a flush */
    134 #endif
    135 
    136 		if (*xtype == 'r') {
    137 			(void)close(pdes[0]);
    138 			if (pdes[1] != STDOUT_FILENO) {
    139 				(void)dup2(pdes[1], STDOUT_FILENO);
    140 				(void)close(pdes[1]);
    141 			}
    142 			if (twoway)
    143 				(void)dup2(STDOUT_FILENO, STDIN_FILENO);
    144 		} else {
    145 			(void)close(pdes[1]);
    146 			if (pdes[0] != STDIN_FILENO) {
    147 				(void)dup2(pdes[0], STDIN_FILENO);
    148 				(void)close(pdes[0]);
    149 			}
    150 		}
    151 
    152 		execl(_PATH_BSHELL, "sh", "-c", command, NULL);
    153 		_exit(127);
    154 		/* NOTREACHED */
    155 	}
    156 	(void)__unlockenv();
    157 
    158 	/* Parent; assume fdopen can't fail. */
    159 	if (*xtype == 'r') {
    160 		iop = fdopen(pdes[0], xtype);
    161 #ifdef _REENTRANT
    162 		cur->fd = pdes[0];
    163 #endif
    164 		(void)close(pdes[1]);
    165 	} else {
    166 		iop = fdopen(pdes[1], xtype);
    167 #ifdef _REENTRANT
    168 		cur->fd = pdes[1];
    169 #endif
    170 		(void)close(pdes[0]);
    171 	}
    172 
    173 	/* Link into list of file descriptors. */
    174 	cur->fp = iop;
    175 	cur->pid =  pid;
    176 	cur->next = pidlist;
    177 	pidlist = cur;
    178 	(void)rwlock_unlock(&pidlist_lock);
    179 
    180 	return (iop);
    181 }
    182 
    183 /*
    184  * pclose --
    185  *	Pclose returns -1 if stream is not associated with a `popened' command,
    186  *	if already `pclosed', or waitpid returns an error.
    187  */
    188 int
    189 pclose(iop)
    190 	FILE *iop;
    191 {
    192 	struct pid *cur, *last;
    193 	int pstat;
    194 	pid_t pid;
    195 
    196 	_DIAGASSERT(iop != NULL);
    197 
    198 	rwlock_wrlock(&pidlist_lock);
    199 
    200 	/* Find the appropriate file pointer. */
    201 	for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
    202 		if (cur->fp == iop)
    203 			break;
    204 	if (cur == NULL) {
    205 		(void)rwlock_unlock(&pidlist_lock);
    206 		return (-1);
    207 	}
    208 
    209 	(void)fclose(iop);
    210 
    211 	/* Remove the entry from the linked list. */
    212 	if (last == NULL)
    213 		pidlist = cur->next;
    214 	else
    215 		last->next = cur->next;
    216 
    217 	(void)rwlock_unlock(&pidlist_lock);
    218 
    219 	do {
    220 		pid = waitpid(cur->pid, &pstat, 0);
    221 	} while (pid == -1 && errno == EINTR);
    222 
    223 	free(cur);
    224 
    225 	return (pid == -1 ? -1 : pstat);
    226 }
    227