Debian Codegraph @

source/extproc.cc

raw
1 // ----------------------------------------------------------------------------
2 //
3 // Copyright (C) 2003-2013 Fons Adriaensen <[email protected]>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 //
18 // ----------------------------------------------------------------------------
19
20
21 #include <unistd.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <sys/types.h>
28 #include <sys/mman.h>
29 #include <sys/stat.h>
30 #include <sys/wait.h>
31 #include "extproc.h"
32
33
34
35 Extproc::Extproc (const char *shmname, size_t shmsize) :
36 _shmem (0)
37 {
38 if (shmsize)
39 {
40 sprintf (_shmname, "/%s-%d", shmname, getpid ());
41 _shmem = new Shmem (_shmname, shmsize, true);
42 }
43 else *_shmname = 0;
44 _procid = 0;
45 _procrc = 0;
46 }
47
48
49 Extproc::~Extproc (void)
50 {
51 wait ();
52 delete _shmem;
53 shm_unlink (_shmname);
54 }
55
56
57 int Extproc::start (const char *prefix, const char *procfile)
58 {
59 int p, k = 0;
60
61 if (prefix) _args [k++] = (char *) prefix;
62 _args [k++] = (char *) procfile;
63 _args [k++] = _shmname;
64 _args [k] = 0;
65 _procid = 0;
66 p = fork ();
67 if (p == 0)
68 {
69 if (execvp (_args [0], _args) < 0)
70 {
71 perror ("execvp");
72 return -1;
73 }
74 }
75 if (p < 0)
76 {
77 perror ("fork:");
78 return -2;
79 }
80 _procid = p;
81 _procrc = 0;
82 return 0;
83 }
84
85
86 int Extproc::kill (void)
87 {
88 if (_procid && ::kill (_procid, SIGINT))
89 {
90 perror ("kill:");
91 return -1;
92 }
93 return 0;
94 }
95
96
97 int Extproc::wait (void)
98 {
99 if (_procid && waitpid (_procid, &_procrc, 0) < 0)
100 {
101 perror ("wait:");
102 return -1;
103 }
104 return 0;
105 }
106