在C中命名为示例



读取器方,

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
        int fd;
        char buff[100];
        fd = open ("MyPipes",O_RDONLY);
        read (fd, buff, 100);
        printf ("%sn",buff);
        close(fd);
}

作家方,

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
char *ptr = "Akshit Soni";
int main()
{
        int fd;
        fd = open ("MyPipes",O_WRONLY);
        write (fd, ptr, strlen(ptr));
        close (fd);
}

问题是读取器程序输出获取垃圾值。

您的(第一个)问题在这里:

write (fd, ptr, strlen(ptr));

"Akshit Soni"strlen dis 不包括尾随的nul字符。您需要使用strlen (ptr) + 1作为长度。

您还应该允许read()不得返回您要求的所有字节(100)或发送的所有字节(包括NUL)。仅通过单个调用read()读取数据的 part 的原因(例如计时或中断)。

为此,您可以尝试以下操作:

int main()
{
    int fd;
    char buff[100];
    fd = open ("MyPipes",O_RDONLY);
    int sz = read (fd, buff, 100);
    while ((sz > 0) && (buff[sz-1] != '')) {
        printf ("%*.*s", sz-1, sz-1, buff);
        sz = read (fd, buff, 100);
    }
    if (sz > 0)
        printf ("%sn",buff);
    close(fd);
}

顺便说一句,请确保您实际上已经创建了在运行代码之前命名的管道,然后使用类似的内容(来自bash):

mkfifo MyPipes

确保您以正确的顺序打开东西;首先打开管道以进行写,然后进行阅读。您没有测试您对管道的开口没有零反应,并且您很可能正在看垃圾。始终测试您功能的返回值...

  1. 创建命名管道是不正确的。使用mkfifo创建

  2. 对于创建文件,可能需要使用更多标志,假设已经存在命名mypipes的此类文件。fd = open(" mypipes",o_wronly | o_creat);没有o_creat,没有创建文件。

  3. 写(fd,ptr,strlen(ptr));将其更改为写(fd,ptr,strlen(ptr) 1);

strlen将返回长度withou" 0"。

您在open时未能添加适当的标志。

尝试以下操作:

fd = open(" mypipe11",o_wronly | o_creat);

编辑:

在使用MKFIFO打开之前,请在作者中创建命名的管道。

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
char *ptr = "Akshit Soni";
int main()
{
        int fd;
        /* Create named pipe */
        mkfifo("MyPipes", 0666);
        /* open named pipe */
        fd = open ("MyPipes",O_WRONLY);
        write (fd, ptr, strlen(ptr));
        close (fd);
}

@paxdiablo已经给出了命令行的命令线方法。

最新更新