如何在C中写入和读取命名管道?

时间:2016-12-06 13:43:15

标签: c named-pipes

我有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

1 个答案:

答案 0 :(得分:5)

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

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

是未定义的行为。你应该做

write(fd, buf, n) != n

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

这很有趣,因为你是为read.c而不是write.c

n的类型必须是ssize_t而不是intman read

main()必须返回int Declare main prototype