2

我想以这样的方式使用一对 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;
}

我做了一些改进,但仍然无法正常工作。

4

2 回答 2

1

fork服务器的 'ed 部分,重定向wcwith的标准输入和输出

dup2(c2s, STDIN_FILENO);
dup2(s2c, STDOUT_FILENO);

然后执行它

execl("/usr/bin/wc", "wc", NULL);

不要将文件描述符作为参数传递给execl. 它需要字符串 ( char const*),而不是int

请参阅dup2POSIX 标准以了解其工作原理。

于 2011-05-06T14:25:26.473 回答
0

请注意,wc将字符串写入其输出。您正试图将它们当作二进制数来读取。这会导致混乱——尤其是当您没有检查读取调用是否正常工作时。

实际上,一般性评论 - 你应该检查更多的系统调用。

您还必须确保您的进程在打开 FIFO 时不会阻塞。你应该没问题;您让进程打开“fifo1”进行读写,然后打开“fifo2”。我认为这会迫使事情有正确的顺序。

您只能在管道上正确写入 4 个字母的文件名。

于 2011-05-11T15:56:38.373 回答