Why does read() not succeed until after the process is killed?

84 Views Asked by At

I'm working on a project that allows a UNIX system to communicate with another machine via a serial connection using cu(1.07).

The following is the approximate framework of the program I'm trying to use, with all of the error-checking and such removed for readability (I have made sure that all of the calls succeed up until read() for both paths)

int main(){
  int toChild[2];
  int fromChild[2];
  pipe(toChild);    //Need to make sure both calls to pipe() succeed
  pipe(fromChild);
  int pid = fork(); //Need to make sure pid >= 0
  if(pid == 0){
     close(toChild[1]);
     close(fromChild[0]);
     dup2(toChild[0],STDIN_FILENO);
     close(toChild[0]);
     dup2(fromChild[1],STDOUT_FILENO);
     close(fromChild[1]);
     execl("/usr/bin/cu","cu",arguments...,(char*)NULL);
  }
  else{
     close(toChild[0]);
     close(fromChild[1]);
     char buf[1024];
     ssize_t len = read(fromChild[0],buf,1023); //Need to make sure is not -1
     buf[len] = '\0';
     printf("%s",buf);
     kill(pid,15);
     waitpid(pid,NULL,0);
     close(toChild[1]);
     close(fromChild[0]);
  }
}

When I call cu from the command line with the exact arguments I'm using in my execl() call, it prints "Connected." and waits, but when I run it via execl() the read() call hangs until I kill the cu process from another terminal, and after it is killed, the read() call succeeds and prints:

Connected.
cu: Got termination signal

Disconnected.

What is happening? Why is read() hung up?

Edit: it may be relevant that I'm using Debian GNU/Linux 10 (Buster)

0

There are 0 best solutions below