Использование функции опроса с буферизованными потоками
Я пытаюсь реализовать систему связи типа клиент-сервер, используяопрос Функция в C. Поток выглядит следующим образом:
Основная программа разветвляется на подпроцессДочерний процесс вызываетexec
функция для выполненияsome_binary
Родитель и потомок отправляют сообщения друг другу поочередно, каждое отправленное сообщение зависит от последнего полученного сообщения.Я пытался реализовать это с помощьюpoll
, но столкнулся с проблемами, потому что дочерний процесс буферизует свой вывод, вызывая мойpoll
звонки на тайм-аут. Вот мой код:
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;
}
}
Код сервера просто:
int main() {
char *buffer = (char *) malloc(1000);
while (scanf("%s", buffer) != EOF)
{
printf("I received %s\n", buffer);
}
return 0;
}
Как я могу предотвратитьpoll
звонки от тайм-аута из-за буферизации?
РЕДАКТИРОВАТЬ:
Я хотел бы, чтобы программа работала, даже когдаexec
двоичный файл ed является внешним, то есть я не имею никакого контроля над кодом - как команда unix, например,cat
или жеls
.