1 //===-- OutputRedirector.cpp -----------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===/
17 #include "OutputRedirector.h"
18 #include "llvm/ADT/StringRef.h"
24 Error
RedirectFd(int fd
, std::function
<void(llvm::StringRef
)> callback
) {
27 if (_pipe(new_fd
, 4096, O_TEXT
) == -1) {
29 if (pipe(new_fd
) == -1) {
32 return createStringError(inconvertibleErrorCode(),
33 "Couldn't create new pipe for fd %d. %s", fd
,
37 if (dup2(new_fd
[1], fd
) == -1) {
39 return createStringError(inconvertibleErrorCode(),
40 "Couldn't override the fd %d. %s", fd
,
44 int read_fd
= new_fd
[0];
45 std::thread
t([read_fd
, callback
]() {
46 char buffer
[OutputBufferSize
];
48 ssize_t bytes_count
= read(read_fd
, &buffer
, sizeof(buffer
));
51 if (bytes_count
== -1) {
52 if (errno
== EAGAIN
|| errno
== EINTR
)
56 callback(StringRef(buffer
, bytes_count
));
60 return Error::success();
63 } // namespace lldb_dap