| 1 |
#include "child.h" |
| 2 |
#include <iostream> |
| 3 |
#include <string> |
| 4 |
#include <cstdlib> |
| 5 |
|
| 6 |
using namespace std; |
| 7 |
|
| 8 |
//CHILD |
| 9 |
void Child::childRedirections() |
| 10 |
{ |
| 11 |
d_in.readFrom(STDIN_FILENO); |
| 12 |
d_out.writtenBy(STDOUT_FILENO); |
| 13 |
} |
| 14 |
//= |
| 15 |
//PARENT |
| 16 |
void Child::parentRedirections() |
| 17 |
{ |
| 18 |
d_parentReadFd = d_out.readOnly(); |
| 19 |
d_parentWriteFd = d_in.writeOnly(); |
| 20 |
} |
| 21 |
//= |
| 22 |
//PROCESS |
| 23 |
void Child::childProcess() |
| 24 |
{ |
| 25 |
Selector selector; |
| 26 |
size_t message = 0; |
| 27 |
|
| 28 |
selector.addReadFd(STDIN_FILENO); |
| 29 |
selector.setAlarm(5); |
| 30 |
|
| 31 |
while (true) |
| 32 |
{ |
| 33 |
try |
| 34 |
{ |
| 35 |
if (!selector.wait()) // timeout |
| 36 |
cout << "Child " << d_nr << ": standing by\n"; |
| 37 |
else |
| 38 |
{ |
| 39 |
string line; |
| 40 |
getline(cin, line); |
| 41 |
cout << "Child " << d_nr << ":" << ++message << ": " << |
| 42 |
line << '\n'; |
| 43 |
} |
| 44 |
} |
| 45 |
catch (...) |
| 46 |
{ |
| 47 |
cout << "Child " << d_nr << ":" << ++message << ": " << |
| 48 |
"select() failed" << '\n'; |
| 49 |
} |
| 50 |
} |
| 51 |
exit(0); |
| 52 |
} |
| 53 |
//= |
| 54 |
|
| 55 |
//CHILDDES |
| 56 |
Child::~Child() |
| 57 |
{ |
| 58 |
if (pid()) |
| 59 |
{ |
| 60 |
cout << "Killing process " << pid() << "\n"; |
| 61 |
kill(pid(), SIGTERM); |
| 62 |
int status; |
| 63 |
wait(&status); |
| 64 |
} |
| 65 |
} |
| 66 |
//= |