File: pipe.c

package info (click to toggle)
shell-fm 0.7%2Bgit20100414-2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 444 kB
  • ctags: 305
  • sloc: ansic: 4,422; makefile: 135; python: 80; haskell: 76; sh: 67; perl: 19
file content (50 lines) | stat: -rw-r--r-- 804 bytes parent folder | download | duplicates (2)
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
/*
	Copyright (C) 2006 by Jonas Kramer
	Published under the terms of the GNU General Public License (GPL).
*/

#define _GNU_SOURCE

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>

#include <errno.h>
#include <string.h>

#include "interface.h"
#include "pipe.h"

FILE * openpipe(const char * cmd, pid_t * cpid) {
	pid_t pid;
	int fd[2] = { 0 };

	assert(cmd);

	if(-1 == pipe(fd)) {
		fprintf(stderr, "Couldn't create pipe. %s.\n", strerror(errno));
		return NULL;
	}

	pid = fork();

	if(pid == -1) {
		fprintf(stderr, "Fork failed. %s.\n", strerror(errno));
		close(fd[1]);
		close(fd[0]);
		return NULL;
	}

	if(!pid) {
		close(fd[1]);
		dup2(fd[0], 0);

		execl("/bin/sh", "sh", "-c", cmd, NULL);
	}

	if(cpid != NULL)
		* cpid = pid;

	return fdopen(fd[1], "w");
}