Merge pull request #2216 from jwillemsen/jwi-cxxversionchecks
[ACE_TAO.git] / ACE / examples / IPC_SAP / FIFO_SAP / FIFO-test.cpp
blobf30c2e744f0db56ad05279fc3d8325b5a66e34c4
1 // Purpose: This program uses ACE_FIFO wrappers to perform
2 // interprocess communication between a parent process and a child
3 // process. The parents reads from an input file and writes it into
4 // the fifo. The child reads from the ACE_FIFO and executes the more
5 // command.
7 #include "ace/FIFO_Recv.h"
8 #include "ace/FIFO_Send.h"
9 #include "ace/Log_Msg.h"
10 #include "ace/OS_NS_sys_wait.h"
11 #include "ace/OS_NS_unistd.h"
12 #include "ace/OS_NS_stdlib.h"
13 #include "ace/OS_NS_fcntl.h"
15 #define PERMS 0666
16 #define EXEC_NAME "more"
17 #define EXEC_COMMAND_ARG "more"
19 static const ACE_TCHAR *FIFO_NAME = ACE_TEXT ("/tmp/fifo");
21 static int
22 do_child (ACE_FIFO_Recv &fifo_reader)
24 // Set child's stdin to read from the fifo.
25 if (ACE_OS::close (ACE_STDIN) == -1
26 || ACE_OS::dup (fifo_reader.get_handle ()) == ACE_INVALID_HANDLE)
27 return -1;
29 char *argv[2];
30 argv[0] = const_cast<char *> (EXEC_COMMAND_ARG);
31 argv[1] = 0;
33 if (ACE_OS::execvp (EXEC_NAME, argv) == -1)
34 return -1;
35 return 0;
38 static int
39 do_parent (const ACE_TCHAR fifo_name[],
40 ACE_TCHAR input_filename[])
42 ACE_FIFO_Send fifo_sender (fifo_name, O_WRONLY | O_CREAT);
43 ssize_t len;
44 char buf[BUFSIZ];
46 if (fifo_sender.get_handle () == ACE_INVALID_HANDLE)
47 return -1;
49 ACE_HANDLE inputfd =
50 ACE_OS::open (input_filename, O_RDONLY);
52 if (inputfd == ACE_INVALID_HANDLE)
53 return -1;
55 // Read from input file and write into input end of the fifo.
57 while ((len = ACE_OS::read (inputfd, buf, sizeof buf)) > 0)
58 if (fifo_sender.send (buf, len) != len)
59 return -1;
61 if (len == -1)
62 return -1;
64 if (fifo_sender.remove () == -1)
65 return -1;
66 return 0;
69 int
70 ACE_TMAIN (int argc, ACE_TCHAR *argv[])
72 ACE_LOG_MSG->open (argv[0]);
74 if (argc != 2)
76 ACE_ERROR ((LM_ERROR,
77 ACE_TEXT ("usage: %n input-file\n"),
78 1));
79 ACE_OS::exit (1);
82 ACE_FIFO_Recv fifo_reader (FIFO_NAME, O_RDONLY | O_CREAT, PERMS, 0);
84 if (fifo_reader.get_handle () == ACE_INVALID_HANDLE)
85 return -1;
87 pid_t const child_pid = ACE_OS::fork ();
89 switch (child_pid)
91 case -1:
92 ACE_ERROR ((LM_ERROR,
93 ACE_TEXT ("%n: %p\n"),
94 ACE_TEXT ("fork"),
95 1));
96 ACE_OS::abort ();
97 case 0:
98 if (do_child (fifo_reader) == -1)
100 ACE_ERROR ((LM_ERROR,
101 ACE_TEXT ("%n: %p\n"),
102 ACE_TEXT ("do_child"),
103 1));
104 ACE_OS::abort ();
106 ACE_FALLTHROUGH;
107 default:
108 if (do_parent (FIFO_NAME, argv[1]) == -1)
110 ACE_ERROR ((LM_ERROR,
111 ACE_TEXT ("%n: %p\n"),
112 ACE_TEXT ("do_parent"),
113 1));
114 ACE_OS::abort ();
117 // wait for child to ACE_OS::exit.
118 if (ACE_OS::waitpid (child_pid, (ACE_exitcode *) 0, 0) == -1)
119 ACE_ERROR ((LM_ERROR,
120 ACE_TEXT ("%n: %p\n%a"),
121 ACE_TEXT ("waitpid"),
122 1));
125 return 0;