对轮询流使用轮询功能
我正在尝试使用C中的poll函数来实现通信系统的客户端-服务器类型。流程如下:
主程序派生一个子进程
子进程调用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;}}如何防止poll由于缓冲而导致呼叫超时?
编辑:
我希望程序即使在execed二进制文件位于外部时也能运行,即我无法控制代码-像unix命令,例如cator ls。
幕布斯6054654
紫衣仙女
SMILET
相关分类