【发布时间】:2012-01-26 12:24:46
【问题描述】:
我正在尝试编写简单的客户端和服务器 C 程序,在不同的终端中相互通信。
服务器必须创建一个公共 fifo 并等待客户端。同时,客户端正在创建自己的先进先出,服务器的响应将通过该先进先出。客户端的任务是向服务器发送队列创建的名称,并返回ls 命令的结果。
我确实搜索了答案,例如:fifo-server-program、example-of-using-named-pipes-in-linux-bash、how-to-send-a-simple-string-between-two-programs-using-pipes。我从第三个链接的代码开始,慢慢修改。
我现在得到的是一个客户端,它从用户那里获取输入,将其发送到服务器并接收回来。但它只工作一次。我不知道为什么。 main函数的主体如下。如有任何帮助,我将不胜感激。
编辑: 我让它工作了! :D 代码如下,也许它会对某人有所帮助。
server.c 代码:
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char* argv[])
{
int fds[2];
char tab[BUFSIZ];
int fd, n;
char *myfifo = "/tmp/serwer";
char *myfifo2 = "/tmp/client";
pipe(fds);
mkfifo(myfifo,0666);
while(1)
{
fds[0]=open(myfifo2,O_RDONLY);
fds[1]=open(myfifo,O_WRONLY);
read(fds[0],tab,BUFSIZ);
if (strcmp("klient",tab)==0) {
printf("Od klienta: %s\n",tab);
fd=open(tab,O_WRONLY);
if(fork()==0)
{
dup2(fds[1],1);
close(fds[1]);
execlp("ls","ls","-l",NULL);
close(fds[0]);
close(fds[1]);
}
else
{
dup2(fds[0],0);
n = read(fds[0],tab,BUFSIZ);
write(fd,tab,n);
close(fds[0]);
close(fds[1]);
}
}
memset(tab, 0, sizeof(tab));
close(fd);
close(fds[0]);
close(fds[1]);
}
unlink(myfifo);
return 0;
}
client.c 代码:
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char* argv[])
{
int fds[2];
char *myfifo = "/tmp/serwer";
char *myfifo2 = "/tmp/client";
mkfifo(myfifo2,0666);
fds[0]=open(myfifo,O_RDONLY);
fds[1]=open(myfifo2,O_WRONLY);
char tab[BUFSIZ];
memset(tab, 0, sizeof(tab));
write(fds[1],"klient",6);
perror("Write:"); //Very crude error check
read(fds[0],tab,sizeof(tab));
perror("Read:"); // Very crude error check
printf("Odebrano od serwera: %s\n",tab);
close(fds[0]);
close(fds[1]);
unlink(myfifo2);
return 0;
}
【问题讨论】:
-
从这段代码中看不出来。您是否使 ls 输出正常工作,或者您只是发送小消息?在这种情况下,通常的陷阱是死锁,即服务器在等待输入,而客户端在等待输入。他们永远等待,因为没有人发送任何东西。
-
不,ls 命令还没有工作。这些程序工作一次——服务器等待消息,将其返回给客户端,客户端可以关闭。当我想发送另一条消息时,客户端和服务器都没有响应。
标签: c linux client-server mkfifo