wibble  0.1.28
childprocess.test.h
Go to the documentation of this file.
1 /* -*- C++ -*- (c) 2007 Petr Rockai <me@mornfall.net>
2  (c) 2007 Enrico Zini <enrico@enricozini.org> */
4 
5 #ifdef POSIX
6 #include <wibble/sys/process.h>
7 #include <wibble/sys/exec.h>
8 #include <cstdlib>
9 #include <iostream>
10 #include <unistd.h>
11 
12 #include <wibble/test.h>
13 
14 
15 using namespace std;
16 using namespace wibble::sys;
17 
18 class EndlessChild : public ChildProcess
19 {
20 protected:
21  int main()
22  {
23  while (true)
24  sleep(60);
25  return 0;
26  }
27 };
28 
29 class TestChild : public ChildProcess
30 {
31 protected:
32  int main()
33  {
34  cout << "antani" << endl;
35  return 0;
36  }
37 };
38 
39 std::string suckFd(int fd)
40 {
41  std::string res;
42  char c;
43  while (true)
44  {
45  int r = read(fd, &c, 1);
46  if (r == 0)
47  break;
48  if (r < 0)
49  throw wibble::exception::System("reading data from file descriptor");
50  res += c;
51  }
52  return res;
53 }
54 
55 struct TestChildprocess {
56 
57  // Try running the child process and kill it
58  Test kill() {
59  EndlessChild child;
60 
61  // Start the child
62  pid_t pid = child.fork();
63 
64  // We should get a nonzero pid
65  assert(pid != 0);
66 
67  // Send SIGQUIT
68  child.kill(2);
69 
70  // Wait for the child to terminate
71  int res = child.wait();
72 
73  // Check that it was indeed terminated by signal 2
74  assert(WIFSIGNALED(res));
75  assert_eq(WTERMSIG(res), 2);
76  }
77 
78  // Try getting the output of the child process
79  Test output() {
80  TestChild child;
81  int out;
82 
83  // Fork the child redirecting its stdout
84  pid_t pid = child.forkAndRedirect(0, &out, 0);
85  assert(pid != 0);
86 
87  // Read the child output
88  assert_eq(suckFd(out), "antani\n");
89 
90  // Wait for the child to terminate
91  assert_eq(child.wait(), 0);
92  }
93 
94  Test redirect() {
95  Exec child("/bin/echo");
96  child.args.push_back("antani");
97  int out;
98 
99  // Fork the child redirecting its stdout
100  pid_t pid = child.forkAndRedirect(0, &out, 0);
101  assert(pid != 0);
102 
103  // Read the child output
104  assert_eq(suckFd(out), "antani\n");
105 
106  // Wait for the child to terminate
107  assert_eq(child.wait(), 0);
108  }
109 
110  Test shellCommand() {
111  ShellCommand child("A=antani; echo $A");
112  int out;
113 
114  // Fork the child redirecting its stdout
115  pid_t pid = child.forkAndRedirect(0, &out, 0);
116  assert(pid != 0);
117 
118  // Read the child output
119  assert_eq(suckFd(out), "antani\n");
120 
121  // Wait for the child to terminate
122  assert_eq(child.wait(), 0);
123  }
124 
125 };
126 #endif
127 // vim:set ts=4 sw=4: