我想以这样的方式使用一对 Unix FIFO:
- 客户端向服务器发送文件名和
- 服务器返回给客户端:给定文件的字数、行数和字节数。
你能帮忙吗?
客户端.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int nr,s2c,c2s,c,d,e;
char a[20];
c2s=open("fifo1",O_WRONLY);
s2c=open("fifo2",O_RDONLY);
printf("give file name \n");
scanf("%s",a);
nr=strlen(a);
write(c2s,&nr,sizeof(int));
write(c2s,&a,sizeof(nr));
read(s2c,&c,sizeof(int));
read(s2c,&d,sizeof(int));
read(s2c,&e,sizeof(int));
close(c2s);
close(s2c);
return 0;
}
服务器.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int nr,s2c,c2s,c,d,e;
char a[20];
FILE* f;
c2s=open("fifo1",O_RDONLY);
s2c=open("fifo2",O_WRONLY);
read(c2s,&nr,sizeof(int));
read(c2s,&a,sizeof(nr));
f=fopen(a,"r");
if(fork()==0)
{
printf("result is: \n");
execl("/usr/bin/wc","wc",c,d,e,NULL);
}
wait(0);
write(s2c,&c,sizeof(int));
write(s2c,&d,sizeof(int));
write(s2c,&e,sizeof(int));
close(c2s);
close(s2c);
printf("\n FINISH \n");
return 0;
}
我做了一些改进,但它仍然不能正常工作。
最佳答案
在服务器的fork
部分,重定向wc
的标准输入和输出
dup2(c2s, STDIN_FILENO);
dup2(s2c, STDOUT_FILENO);
然后执行它
execl("/usr/bin/wc", "wc", NULL);
不要将文件描述符作为参数传递给 execl
。它需要字符串 (char const*
),而不是 int
。
参见 dup2
in the POSIX standard了解其工作原理。
关于c - Unix fifo 客户端到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5912715/