c - Unix fifo 客户端到服务器

标签 c unix fifo

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

相关文章:

c++ - FSEvent 无法在根上下文 : Error: FSEventStreamCreate: _FSEventStreamCreate: ERROR: watch_path() failed for 中创建流

c - 打印期间意外的字符串行为

c - 将字符串解析为(long long)整数

c - 如果没有用户输入(在 C 中)

unix - Makefile ifeq 逻辑与

linux - 计算字符在 unix 中的字符串中出现的次数

c - 使符号链接(symbolic link)到可执行文件

go - 有队列实现吗?

C 命名管道 (fifo)。父进程卡住

python - 在一个模块中打开命名管道,在另一个模块中读取