1 |
#ifndef lint |
2 |
static const char RCSid[] = "$Id: unix_process.c,v 3.5 2004/09/17 21:43:49 greg Exp $"; |
3 |
#endif |
4 |
/* |
5 |
* Routines to communicate with separate process via dual pipes |
6 |
* Unix version |
7 |
* |
8 |
* External symbols declared in standard.h |
9 |
*/ |
10 |
|
11 |
#include "copyright.h" |
12 |
|
13 |
#include <sys/types.h> |
14 |
#include <sys/wait.h> |
15 |
#include <fcntl.h> |
16 |
|
17 |
#include "rtprocess.h" |
18 |
|
19 |
|
20 |
int |
21 |
open_process( /* open communication to separate process */ |
22 |
SUBPROC *pd, |
23 |
char *av[] |
24 |
) |
25 |
{ |
26 |
extern char *getpath(), *getenv(); |
27 |
char *compath; |
28 |
int p0[2], p1[2]; |
29 |
|
30 |
pd->running = 0; /* not yet */ |
31 |
/* find executable */ |
32 |
compath = getpath(av[0], getenv("PATH"), 1); |
33 |
if (compath == 0) |
34 |
return(0); |
35 |
if (pipe(p0) < 0 || pipe(p1) < 0) |
36 |
return(-1); |
37 |
if ((pd->pid = fork()) == 0) { /* if child */ |
38 |
close(p0[1]); |
39 |
close(p1[0]); |
40 |
if (p0[0] != 0) { /* connect p0 to stdin */ |
41 |
dup2(p0[0], 0); |
42 |
close(p0[0]); |
43 |
} |
44 |
if (p1[1] != 1) { /* connect p1 to stdout */ |
45 |
dup2(p1[1], 1); |
46 |
close(p1[1]); |
47 |
} |
48 |
execv(compath, av); /* exec command */ |
49 |
perror(compath); |
50 |
_exit(127); |
51 |
} |
52 |
if (pd->pid == -1) |
53 |
return(-1); |
54 |
close(p0[0]); |
55 |
close(p1[1]); |
56 |
pd->r = p1[0]; |
57 |
pd->w = p0[1]; |
58 |
/* |
59 |
* Close write stream on exec to avoid multiprocessing deadlock. |
60 |
* No use in read stream without it, so set flag there as well. |
61 |
* GW: This bug took me two days to figure out!! |
62 |
*/ |
63 |
fcntl(pd->r, F_SETFD, FD_CLOEXEC); |
64 |
fcntl(pd->w, F_SETFD, FD_CLOEXEC); |
65 |
pd->running = 1; |
66 |
return(PIPE_BUF); |
67 |
} |
68 |
|
69 |
|
70 |
|
71 |
int |
72 |
close_process( /* close pipes and wait for process */ |
73 |
SUBPROC *pd |
74 |
) |
75 |
{ |
76 |
int pid, status; |
77 |
|
78 |
if (!pd->running) |
79 |
return(0); |
80 |
close(pd->r); |
81 |
close(pd->w); |
82 |
pd->running = 0; |
83 |
if (waitpid(pd->pid, &status, 0) == pd->pid) |
84 |
return(status>>8 & 0xff); |
85 |
return(-1); /* ? unknown status */ |
86 |
} |
87 |
|
88 |
|