I noticed the same problem with losses when I write to the fd master.
Problems can be avoided by using slave fd to write. And master fd for stdin baby. In this way:
int main(void) { int master_fd = -1; int slave_fd = -1; if( openpty( &master_fd, &slave_fd, NULL, NULL, NULL ) != -1 ) { const pid_t child_pid = fork(); if( child_pid != -1 ) { if( child_pid ) { const char command[] = "command\n"; close( master_fd ); write( slave_fd, command, strlen(command) ); close( slave_fd ); } else { close( slave_fd ); dup2( master_fd, STDIN_FILENO ); execlp( "/bin/cat", "cat", (char*)0 ); } } } return 0; }
You can even add delays to the child process, and it still works. Thus, the parent process can exit before the child process does something:
~ # temp_test ~ # command cat: read error: Input/output error ~ #
EDIT:
A slightly different example, because a printing error from a cat is embarrassing:
if( child_pid ) { const char command[] = "command\n"; close( master_fd ); write( slave_fd, command, sizeof(command) ); close( slave_fd ); } else { char buffer[100]; ssize_t i; ssize_t len; close( slave_fd ); do { len = read( master_fd, buffer, sizeof(buffer) ); for( i = 0; i < len; i++ ) printf("%c", buffer[i] ); } while( len > 0 ); }
And the result:
~
source share