WvStreams
wvsystem.cc
1 /*
2  * Worldvisions Weaver Software:
3  * Copyright (C) 1997-2002 Net Integration Technologies, Inc.
4  *
5  * A more convenient wrapper around WvSubProc. See wvsystem.h.
6  */
7 #include "wvsystem.h"
8 #include <unistd.h>
9 #include <fcntl.h>
10 #include <sys/types.h>
11 
13 {
14  go();
15 }
16 
17 
18 void WvSystem::init(const char * const *argv)
19 {
20  started = false;
21  WvSubProc::preparev(argv[0], argv);
22 }
23 
24 
25 // open a given filename or device, making sure it has the given fd. If
26 // there is an open file on that fd already, it gets closed.
27 static void fd_open(int fd, WvStringParm file, int mode)
28 {
29  ::close(fd);
30  int nfd = ::open(file, mode, 0666);
31  if (nfd < 0)
32  return;
33  if (nfd != fd)
34  {
35  ::dup2(nfd, fd);
36  ::close(nfd);
37  }
38 }
39 
40 
41 // overrides WvSubProc::fork().
42 int WvSystem::fork(int *waitfd)
43 {
44  int pid = WvSubProc::fork(waitfd);
45  if (!pid) // child
46  {
47  if (!fdfiles[0].isnull())
48  fd_open(0, fdfiles[0], O_RDONLY);
49  if (!fdfiles[1].isnull())
50  fd_open(1, fdfiles[1], O_WRONLY|O_CREAT);
51  if (!fdfiles[2].isnull())
52  fd_open(2, fdfiles[2], O_WRONLY|O_CREAT);
53  }
54 
55  return pid;
56 }
57 
58 
60 {
61  if (!started)
62  {
63  WvSubProc::start_again();
64  started = true;
65  }
66  WvSubProc::wait(-1, false);
67  return WvSubProc::estatus;
68 }
69 
70 
71 WvSystem &WvSystem::infile(WvStringParm filename)
72 {
73  fdfiles[0] = filename;
74  return *this;
75 }
76 
77 
78 WvSystem &WvSystem::outfile(WvStringParm filename)
79 {
80  fdfiles[1] = filename;
81  return *this;
82 }
83 
84 
85 WvSystem &WvSystem::errfile(WvStringParm filename)
86 {
87  fdfiles[2] = filename;
88  return *this;
89 }
90 
91 
WvSystem::outfile
WvSystem & outfile(WvStringParm filename)
Redirect stdout to the given output file, which is overwritten.
Definition: wvsystem.cc:78
WvSystem::errfile
WvSystem & errfile(WvStringParm filename)
Redirect stderr to the given output file, which is overwritten.
Definition: wvsystem.cc:85
WvSystem::go
int go()
Explicitly start the command running and wait for it to finish.
Definition: wvsystem.cc:59
WvSystem
WvSystem is a mostly-replacement for the libc system() function call, which people usually use becaus...
Definition: wvsystem.h:29
WvSystem::infile
WvSystem & infile(WvStringParm filename)
Redirect stdin from the given input file.
Definition: wvsystem.cc:71
WvSystem::~WvSystem
virtual ~WvSystem()
Destroy the WvSystem object.
Definition: wvsystem.cc:12