1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROMEOS_PROCESS_PROXY_PROCESS_OUTPUT_WATCHER_H_
6 #define CHROMEOS_PROCESS_PROXY_PROCESS_OUTPUT_WATCHER_H_
10 #include "base/callback.h"
11 #include "base/files/file.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "chromeos/chromeos_export.h"
18 enum ProcessOutputType
{
19 PROCESS_OUTPUT_TYPE_OUT
,
20 PROCESS_OUTPUT_TYPE_EXIT
23 typedef base::Callback
<void(ProcessOutputType
, const std::string
&)>
24 ProcessOutputCallback
;
26 // Observes output on |out_fd| and invokes |callback| when some output is
27 // detected. It assumes UTF8 output.
28 class CHROMEOS_EXPORT ProcessOutputWatcher
29 : public base::MessageLoopForIO::Watcher
{
31 ProcessOutputWatcher(int out_fd
, const ProcessOutputCallback
& callback
);
32 ~ProcessOutputWatcher() override
;
37 // MessageLoopForIO::Watcher overrides:
38 void OnFileCanReadWithoutBlocking(int fd
) override
;
39 void OnFileCanWriteWithoutBlocking(int fd
) override
;
41 // Listens to output from fd passed to the constructor.
42 void WatchProcessOutput();
44 // Reads data from fd and invokes callback |on_read_callback_| with read data.
45 void ReadFromFd(int fd
);
47 // Checks if the read buffer has any trailing incomplete UTF8 characters and
48 // returns the read buffer size without them.
49 size_t OutputSizeWithoutIncompleteUTF8();
51 // Processes new |read_buffer_| state and notifies observer about new process
53 void ReportOutput(ProcessOutputType type
, size_t new_bytes_count
);
55 char read_buffer_
[256];
56 // Maximum read buffer content size.
57 size_t read_buffer_capacity_
;
58 // Current read bufferi content size.
59 size_t read_buffer_size_
;
61 // Contains file descsriptor to which watched process output is written.
62 base::File process_output_file_
;
63 base::MessageLoopForIO::FileDescriptorWatcher output_file_watcher_
;
65 // Callback that will be invoked when some output is detected.
66 ProcessOutputCallback on_read_callback_
;
68 base::WeakPtrFactory
<ProcessOutputWatcher
> weak_factory_
;
70 DISALLOW_COPY_AND_ASSIGN(ProcessOutputWatcher
);
73 } // namespace chromeos
75 #endif // CHROMEOS_PROCESS_PROXY_PROCESS_OUTPUT_WATCHER_H_