@@ -32,11 +32,14 @@ namespace tinykvm
3232 : m_machine(machine),
3333 m_current_working_directory_fd (AT_FDCWD)
3434 {
35- // XXX: TODO: Create proper redirects for stdout/stderr by
36- // for example providing a pipe to stdout/stderr.
37- m_fds[0 ] = Entry{ .real_fd = 0 , .is_writable = false }; // stdin
38- m_fds[1 ] = Entry{ .real_fd = 1 , .is_writable = true }; // stdout
39- m_fds[2 ] = Entry{ .real_fd = 2 , .is_writable = true }; // stderr
35+ // Create proper redirects for stdin/stdout/stderr
36+ const int stdout_fd = dup (1 );
37+ const int stderr_fd = dup (2 );
38+ if (stdout_fd < 0 || stderr_fd < 0 ) {
39+ throw std::runtime_error (" TinyKVM: Failed to duplicate stdout/stderr" );
40+ }
41+ m_fds[1 ] = Entry{ .real_fd = stdout_fd, .is_writable = true }; // stdout
42+ m_fds[2 ] = Entry{ .real_fd = stderr_fd, .is_writable = true }; // stderr
4043 }
4144
4245 FileDescriptors::~FileDescriptors ()
@@ -48,6 +51,16 @@ namespace tinykvm
4851 }
4952 }
5053
54+ void FileDescriptors::duplicate_and_add_stdin ()
55+ {
56+ // Create a duplicate of stdin (0) and add it to the list of managed FDs.
57+ const int stdin_fd = dup (0 );
58+ if (stdin_fd < 0 ) {
59+ throw std::runtime_error (" TinyKVM: Failed to duplicate stdin" );
60+ }
61+ m_fds[0 ] = Entry{ .real_fd = stdin_fd, .is_writable = false }; // stdin
62+ }
63+
5164 void FileDescriptors::reset_to (const FileDescriptors& other)
5265 {
5366 // Close all current file descriptors, except if forked
@@ -166,7 +179,8 @@ namespace tinykvm
166179
167180 int FileDescriptors::manage (int fd, bool is_socket, bool is_writable)
168181 {
169- if (fd < 0 ) {
182+ (void )is_socket; // Unused
183+ if (fd <= 2 ) {
170184 throw std::runtime_error (" TinyKVM: Invalid file descriptor in FileDescriptors::add()" );
171185 }
172186 if (this ->m_max_total_fds_opened != 0 && this ->m_total_fds_opened >= this ->m_max_total_fds_opened ) {
@@ -213,7 +227,7 @@ namespace tinykvm
213227 FileDescriptors::Entry& FileDescriptors::manage_as (int vfd, int fd, bool is_socket, bool is_writable)
214228 {
215229 (void )is_socket; // Unused
216- if (fd < 0 ) {
230+ if (fd <= 2 ) {
217231 throw std::runtime_error (" TinyKVM: Invalid fd in FileDescriptors::manage_as()" );
218232 }
219233 if (this ->m_max_total_fds_opened != 0 &&
0 commit comments