#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
int main() {
pid_t c[2];
int p[2];
pipe(p);
c[0] = fork();
if (c[0] < 0) {
fprintf(stderr, "fork error");
exit(EXIT_FAILURE);
} else if (c[0] == 0) {
// First child
close(p[1]); // unuse
close(STDIN_FILENO);
dup(p[0]);
char buf[BUFSIZ];
read(STDIN_FILENO, buf, BUFSIZ);
printf("Second child's print: %s\n", buf); // First Child's print
} else {
c[1] = fork();
if (c[1] < 0) {
fprintf(stderr, "fork error");
exit(EXIT_FAILURE);
}
else if (c[1] == 0) {
// Second child
close(p[0]); // unuse
close(STDOUT_FILENO);
dup(p[1]);
printf("HI"); // Second child's print
}
else if (waitpid(c[0], NULL, 0) == -1 || waitpid(c[1], NULL, 0) == -1) {
exit(EXIT_FAILURE);
}
}
return 0;
}
我写了一段代码,第一个子元素通过read()函数从第一个子元素那里获得第二个子元素的write()函数的消息.
如果第一个子元素是在打印HI之前收获的,我是否有可能无法打印?
如果有可能,如何解决?