下面的代码显示了子进程如何写入管道端以及父进程如何从另一端读取。在我对代码进行试验后,我注意到只有在子进程终止后,父进程才能读取数据。
有没有办法强制父进程在子进程调用write()后立即进入前台并读取数据?有没有办法在不终止孩子的情况下读取数据?
#include <stdio.h> /* For printf */
#include <string.h> /* For strlen */
#include <stdlib.h> /* For exit */
#define READ 0 /* Read end of pipe */
#define WRITE 1 /* Write end of pipe */
char *phrase = "This is a test phrase.";
main(){
int pid, fd[2], bytes;
char message[100];
if (pipe(fd) == -1) { /* Create a pipe */
perror("pipe");
exit(1);
}
if ((pid = fork()) == -1) { /* Fork a child */
perror("fork");
exit(1);
}
if (pid == 0) { /* Child, writer */
close(fd[READ]); /* Close unused end */
write(fd[WRITE], phrase, strlen(phrase)+1);
close(fd[WRITE]); /* Close used end */
}
else { /* Parent, reader */
close(fd[WRITE]); /* Close unused end */
bytes = read(fd[READ], message, sizeof(message));
printf("Read %d bytes: %s\n", bytes, message);
close(fd[READ]); /* Close used end */
}
}