我试图使用poll函数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的二进制是外部的,即I没有控制权的代码 - 就像一个unix命令,例如,cat
或ls
。
为什么子进程关闭所有管道? 'close(wpipe [0]);关闭(RPIPE [0]); close(wpipe [1]);关闭(rpipe [1]);'???? –
@GiuseppePes:fds被复制为标准输入/标准输出,因此关闭它们似乎没问题。 –
@MartinR谢谢!我错过了dub2电话! :( –