summaryrefslogtreecommitdiff
path: root/src/util.c
blob: a5e7c02c276343c993f27de10dcf46432335de5b (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
//
// Copyright 2007 Johannes Hofmann <Johannes.Hofmann@gmx.de>
//
// This software may be used and distributed according to the terms
// of the GNU General Public License, incorporated herein by reference.

#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;
  }
}