简体   繁体   中英

Output written twice and overlapping after pipe and fork

When I compile and run the following code:

#include <stdlib.h>
#include <unistd.h>

#define N 20

int main() {
  int fd[2], p, n;
  char c[N];

  pipe(fd);
  p = fork();

  if (p == 0) {
    dup2(fd[1], 1);
    execlp("date" , "date" , NULL);
    write(fd[1], "Bye", 3);
  }
  else {
    close(fd [1]);
    while((n=read(fd[0], &c, N)) > 0) write(1, &c, N);
  }
  exit (0);
}

the output is the following:

Wed May 27 15:28:21 CEST 2020
 15:28:21 

It looks like the output of date is written twice and it gets overlapped but I don't understand why and how. I see there are two file descriptors for the output (via dup2) but date is executed only once and its output is fed to the parent's input side of the pipe. How is it that a second partial date string gets appended?

Thanks in advance!

Because you're passing N to write instead of n , so when read does a partial read, you ending up writing out extra bytes from the last read again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM