Używanie funkcji odpytywania z buforowanymi strumieniami
Próbuję zaimplementować system komunikacyjny typu klient-serwer przy użyciugłosowanie funkcja w C. Przepływ jest następujący:
Główny program rozwidla podprocesProces potomny wywołujeexec
funkcja do wykonaniasome_binary
Rodzic i dziecko wysyłają wiadomości do siebie naprzemiennie, każda wysłana wiadomość zależy od ostatniej otrzymanej wiadomości.Próbowałem zaimplementować to użyciepoll
, ale wpadł w problemy, ponieważ proces potomny buforuje jego wyjście, powodując mojepoll
połączenia z limitem czasu. Oto mój kod:
int main() {
char *buffer = (char *) malloc(1000);
int n;
pid_t pid; /* pid of child process */
int rpipe[2]; /* pipe used to read from child process */
int wpipe[2]; /* pipe used to write to child process */
pipe(rpipe);
pipe(wpipe);
pid = fork();
if (pid == (pid_t) 0)
{
/* child */
dup2(wpipe[0], STDIN_FILENO);
dup2(rpipe[1], STDOUT_FILENO);
close(wpipe[0]); close(rpipe[0]);
close(wpipe[1]); close(rpipe[1]);
if (execl("./server", "./server", (char *) NULL) == -1)
{
fprintf(stderr, "exec failed\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
else
{
/* parent */
/* close the other ends */
close(wpipe[0]);
close(rpipe[1]);
/*
poll to check if write is good to go
This poll succeeds, write goes through
*/
struct pollfd pfds[1];
pfds[0].fd = wpipe[1];
pfds[0].events = POLLIN | POLLOUT;
int pres = poll(pfds, (nfds_t) 1, 1000);
if (pres > 0)
{
if (pfds[0].revents & POLLOUT)
{
printf("Writing data...\n");
write(wpipe[1], "hello\n", 6);
}
}
/*
poll to check if there's something to read.
This poll times out because the child buffers its stdout stream.
*/
pfds[0].fd = rpipe[0];
pfds[0].events = POLLIN | POLLOUT;
pres = poll(pfds, (nfds_t) 1, 1000);
if (pres > 0)
{
if (pfds[0].revents & POLLIN)
{
printf("Reading data...\n");
int n = read(rpipe[0], buffer, 1000);
buffer[n] = '\0';
printf("child says:\n%s\n", buffer);
}
}
kill(pid, SIGTERM);
return EXIT_SUCCESS;
}
}
Kod serwera jest po prostu:
int main() {
char *buffer = (char *) malloc(1000);
while (scanf("%s", buffer) != EOF)
{
printf("I received %s\n", buffer);
}
return 0;
}
Jak mogę zapobiecpoll
połączenia z limitu czasu z powodu buforowania?
EDYTOWAĆ:
Chciałbym, aby program działał nawet wtedy, gdyexec
ed binary jest zewnętrzny, tj. nie mam kontroli nad kodem - jak polecenie unix, np.cat
lubls
.