繁体   English   中英

如何在C中的命名管道中读写?

[英]How to write and read from a named pipe in C?

我有2个程序(write.c和read.c)。 我想从标准输入连续写入命名管道,并在另一端从命名管道读取(并写入标准输出)。 我已经做了一些工作,但是工作不正常。 另一端的程序读取顺序错误或读取特殊字符(因此读取的内容超出了所需的数量?)。 我还希望能够将命名管道输出与某个字符串进行比较。

无论如何,这是两个文件中的代码:

write.c:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFSIZE 512
#define err(mess) { fprintf(stderr,"Error: %s.", mess); exit(1); }

void main()
{
    int fd, n;

    char buf[BUFFSIZE];


    mkfifo("fifo_x", 0666);
    if ( (fd = open("fifo_x", O_WRONLY)) < 0)
        err("open")

    while( (n = read(STDIN_FILENO, buf, BUFFSIZE) ) > 0) {
        if ( write(fd, buf, strlen(buf)) != strlen(buf)) { 
            err("write");
        }
    }
    close(fd);
}

read.c:

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFSIZE 512
#define err(mess) { fprintf(stderr,"Error: %s.", mess); exit(1); }

void main()
{
    int fd, n;
    char buf[BUFFSIZE];

    if ( (fd = open("fifo_x", O_RDONLY)) < 0)
        err("open")


    while( (n = read(fd, buf, BUFFSIZE) ) > 0) {

        if ( write(STDOUT_FILENO, buf, n) != n) { 
            exit(1);
        }
    }
    close(fd);
}

输入示例:

hello how are you
123 
test

错误输出示例:

hello how are you
b123
o how are you
btest
 how are you
b

输入的另一个示例:

test
hi

并输出:

test
hi
t

通过读取修改的缓冲区不是有效的c字符串,因此

write(fd, buf, strlen(buf)) != strlen(buf) // write.c

是不确定的行为。 你应该做

write(fd, buf, n) != n

因为您使用read()读取了n个八位位组。

这很有趣,因为您为read.c而不是为write.c这样做


男子读n的类型必须是ssize_t而不是int


main()必须返回int 声明main原型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM