gpt4 book ai didi

连接 Fifos(客户端/服务器程序)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:29:45 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的客户端/服务器程序,并在此过程中学习如何使用 Fifos。

程序创建一个 fifo (FifoServer__) 并在打开时阻塞,这是预期的。但是,当我从另一端打开它时,它也会阻塞!我查看了几个示例并尝试了很多方法,但我无法弄清楚。

如有任何提示,我们将不胜感激。

//header.h


# include <stdlib.h>
# include <fcntl.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <unistd.h>
# include <stdio.h>
# include <errno.h>
# include <signal.h>
# include <stdarg.h>

#define fifoServer "FifoServer__"

服务器.c:

# include "header.h"

int main(int argc, char ** argv)
{
int serverfd;
int client_pid;

if (mkfifo( fifoServer, S_IRUSR | S_IWUSR | S_IWGRP) == -1) {
perror("could not mkfifo");
exit(EXIT_FAILURE);
}

serverfd = open(fifoServer, O_RDONLY); //It blocks right here.
if (serverfd == -1) {
perror("failed to open fifo");
exit(EXIT_FAILURE);
}

//Signal handeling
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
perror("Could not Ignore SIGPIPE. Error: %d\n");
exit(EXIT_FAILURE);
}

//listening for connections requests (client's pid)
while (1) {
if (read(serverfd, &client_pid, sizeof(client_pid)))
printf("Client's pid: %d", client_pid);
break;
}

// Unlinking and cleaning Fifoserver__
close(serverfd);
unlink(fifoServer);
remove(fifoServer);

return 0;
}

客户:

# include "header.h"

int main(int argc, char ** argv)
{
int serverfd;
int client_pid;

client_pid = getpid();

serverfd = open(fifoServer, O_WRONLY); //It blocks right here
if (serverfd == -1) {
perror("failed to open fifo");
exit(EXIT_FAILURE);
}

if (write(serverfd, &client_pid, sizeof(client_pid)) == -1) {
perror("Could not open Client Fifo Writer. Error: %d\n");
exit(EXIT_FAILURE);
}

printf("Success !\n");
close(serverfd);
unlink(fifoServer);
return 0;
}

最佳答案

看看这篇关于非阻塞 I/O 的文章 http://cr.yp.to/unix/nonblock.html

关于连接 Fifos(客户端/服务器程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29307419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com