我有一个产生子脚本的程序。子脚本只是将任何输入的 1/2 时间重新发送回 STDOUT 和 STDERR。另一半时间,它悄悄地消耗它。我得到的是写给孩子的结果的时间错误:
Line1: STDOUT Line number 1
Line3: STDERR Line number 1
Line3: STDOUT Line number 3
Getting leftovers
endLine: STDERR Line number 3
第 1 行应该是通过相同的 Line1 读取的。同样,第 3 行也应该被相同的 Line3 尝试拾取。
我要解决的问题是我希望能够向孩子写入一行数据,检查任何响应并重复。以下是测试程序:
子脚本:
#! /usr/bin/perl
$| = 1;
select (STDERR);
$|=1;
my $i = 0;
open (F,">> e.out");
select F;
$|=1;
select (STDOUT);
while (<>) {
chomp;
print F "($_)\n";
if ($i++) {
print "STDOUT $_\n";
print STDERR "STDERR $_\n";
}
$i %= 2;
}
close F;
父 C 程序:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
main () {
pid_t pid;
int p2child[2];
int c2parent[2];
pipe (p2child);
pipe (c2parent);
if ((pid = fork()) < 0) {
fprintf (stderr, "Fork error: %s\n", strerror(errno));
/*
Child Process
*/
} else if (pid == 0) {
close (p2child[1]);
dup2 (p2child[0], STDIN_FILENO);
close (c2parent[0]);
dup2 (c2parent[1], STDOUT_FILENO);
dup2 (c2parent[1], STDERR_FILENO);
if (execlp ("./e", "./e", 0 )) {
perror("Exec failed");
}
/*
Parent Process
*/
} else {
FILE* istream;
FILE* ostream;
char line[80];
fd_set set;
struct timeval timeout;
int ret;
int counter;
close (p2child[0]);
close (c2parent[1]);
ostream = fdopen (p2child[1], "w");
istream = fdopen (c2parent[0], "r");
for (counter = 0; counter < 5; counter++) {
fprintf (ostream, "Line number %d\n", counter);
fflush (ostream);
do {
FD_ZERO(&set);
FD_SET(c2parent[0], &set);
timeout.tv_sec = 0;
timeout.tv_usec = 500000;
ret = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
if (ret > 0) {
fgets(line, 80, istream);
fprintf (stdout, "Line%d: %s", counter, line);
fflush (stdout);
}
} while (ret > 0);
}
fprintf (stdout, "Getting leftovers\n");
while (fgets(line, 80, istream)) {
fprintf (stdout, "endLine: %s", line);
fflush (stdout);
}
close (p2child[1]);
close (c2parent[0]);
waitpid (pid, NULL, 0);
}
fprintf (stderr, "Exiting\n");
}