Subject: using forkpty
To: None <tech-misc@netbsd.org>
From: Felix Zaslavskiy <felix@students.poly.edu>
List: tech-misc
Date: 03/16/2003 02:13:29
Here is a program i wrote that not working as i expected.
Why is it that i dont get the data back from the process that receives 
the pty ?
i also have the file at http://osiris.poly.edu/~felix/src/main.c <http://osiris.poly.edu/%7Efelix/src/main.c>

#include<stdio.h>
#include<stdlib.h>
#include<util.h>


int main()
{
         int pty_pid;
         int ptyfd;

         //create a new process on a new pty
         pty_pid = forkpty(&ptyfd, NULL, NULL, NULL);

         if(pty_pid == -1){
                 printf("error forking pty");
                 exit(0);
         }
         else if(pty_pid == 0)
         {
                 //i am the new process
                 char buf[64];

                 if(!fgets( buf, 63 , stdin))
                         perror("read from parent");

                 buf[33] = 'x';
                 buf[63] = 0;

                 if(!fputs( buf, stdout))
                         perror("write to parent");

                 exit(0);
         }
         else
         {
                 char buf[64];
                 int i = 0;
                 for(; i < 63; ++i)
                 {
                         buf[i] = '0' + i%10;
                 }
                 buf[63]=0;

                 if(fork() == 0)
                {
                         if(write(ptyfd, buf , 64 ) == -1)
                         {
                                 perror("write to child");
                         }
                 }
                 else
                 {
                         if(read(ptyfd, buf , 63) != -1)
                         {
                                 printf("child wrote: %s\n", buf);
                         }
                         else
                         {
                                 perror("read from child:");
                         }
                         close(ptyfd);

                         if(wait() == pty_pid){
                                 printf("Child exited");
                         }
                 }
         }

         return 0;
}