summaryrefslogtreecommitdiff
path: root/src/util.c
blob: f33c1b4711a530f3bbbf212440186b3d8867dfaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* 
 * "$Id: util.c,v 1.1 2005/02/28 17:56:51 hofmann Exp $"
 *
 * flpsed program.
 *
 * Copyright 2005 by Johannes Hofmann
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA.
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "util.h"

FILE *
pexecvp(const char *file, char *const argv[], pid_t *pid, char *type) {
  FILE *iop;
  int   pdes[2];

  if (pipe(pdes) < 0) {
    return NULL;
  }
	
  *pid = vfork();

  if (*pid == -1) {
    perror("vfork");
    close(pdes[0]);
    close(pdes[1]);
    return NULL;
  } else if (*pid == 0) {
    /* child */
    
    if (*type == 'r') {
      close(pdes[0]);
      if (pdes[1] != STDOUT_FILENO) {
	dup2(pdes[1], STDOUT_FILENO);
	close(pdes[1]);
      }
    } else {
      close(pdes[1]);
      if (pdes[0] != STDIN_FILENO) {
	dup2(pdes[0], STDIN_FILENO);
	close(pdes[0]);
      }
    }

    execvp(file, argv);
    exit(127);
  } else {
    /* parent */ 
    if (*type == 'r') {
      iop = fdopen(pdes[0], "r");
      close(pdes[1]);
    } else {
      iop = fdopen(pdes[1], "w");
      close(pdes[0]);
    }
    return iop;
  }
}