简体   繁体   English

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

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

I have 2 programs (write.c and read.c). 我有2个程序(write.c和read.c)。 I want to continuously write to the named pipe from standard input, and read from it on the other end (and write to standard output). 我想从标准输入连续写入命名管道,并在另一端从命名管道读取(并写入标准输出)。 I've made something work, but it isn't working right. 我已经做了一些工作,但是工作不正常。 The program on the other end reads in the wrong order or reads special characters (so it reads more then it needs?). 另一端的程序读取顺序错误或读取特殊字符(因此读取的内容超出了所需的数量?)。 I also want to be able to compare the named pipe output to a certain string. 我还希望能够将命名管道输出与某个字符串进行比较。

Anyways, here's the code from both files: 无论如何,这是两个文件中的代码:

write.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: 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);
}

Example of input: 输入示例:

hello how are you
123 
test

Example of incorrect output: 错误输出示例:

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

Another example of input: 输入的另一个示例:

test
hi

And output: 并输出:

test
hi
t

The buffer modify by read is not a valid c string so 通过读取修改的缓冲区不是有效的c字符串,因此

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

is undefined behaviour. 是不确定的行为。 You should do 你应该做

write(fd, buf, n) != n

because you read n octet with read() . 因为您使用read()读取了n个八位位组。

It's funny because you do it for read.c but not for write.c 这很有趣,因为您为read.c而不是为write.c这样做


The type of n must but ssize_t and not int , man read . 男子读n的类型必须是ssize_t而不是int


main() must return a int Declare main prototype main()必须返回int 声明main原型

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

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