C通过命名管道发送分配的字符串 - linux

标签 c linux

我想通过命名管道发送分配的字符串,而不是简单的字符数组。

我得到了以下代码:

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

int main()
{
    int pid, fd;
    fd = mkfifo("fifo.ftc", S_IRUSR | S_IWUSR);
    pid = fork();

    char* send, * recieve;

    if(pid == 0) {
        recieve = malloc(100);
        fd = open("fifo.ftc", O_RDONLY);
        read(fd, recieve, sizeof(recieve));
        close(fd);
        printf("%s\n", recieve);

        send = malloc(100);
        send = "This text was sent by child!";
        fd = open("fifo.ftc", O_WRONLY);
        write(fd, send, sizeof(send));
        close(fd);

        free(recieve);
        free(send);

    } else if(pid > 0) {
        send = malloc(100);
        send = "This text was sent by parent!";
        fd = open("fifo.ftc", O_WRONLY);
        write(fd, send, sizeof(send));
        close(fd);

        recieve = malloc(100);
        fd = open("fifo.ftc", O_RDONLY);
        read(fd, recieve, sizeof(recieve));
        close(fd);
        printf("%s\n", recieve);

        unlink("fifo.ftc");

        free(send);
        free(recieve);
    }
}

作为输出,我总是收到:

This tex
This tex

看起来它并没有打印出整个字符串。如何接收父子的完整消息?

最佳答案

您的代码中有多个错误。

  1. 你必须记住 readwrite不保证他们会有效地读取或写入您告诉他们的字节数。

    来自 Linux write 手册页:

    Synopsis

    #include <unistd.h>

    ssize_t write(int fd, const void *buf, size_t count);

    Description

    write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd. The number of bytes written may be less than count if, for example, there is insufficient space on the underlying physical medium, or the RLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or the call was interrupted by a signal handler after having written less than count bytes. (See also pipe(7).)

    它们返回读取或写入的字节数,因此您必须将它们的返回值存储在变量中并相应地进行处理。您通常会将它们包装在一个循环中,保留一个计数器来累计读取/写入的字节数,并在达到原始缓冲区大小时或返回错误值时退出循环。

  2. 正如@wildplasser 在评论中提到的,您滥用了 sizeof 运算符。当你执行 char *foo; sizeof foo;,得到的大小不是foo指向的字符串的大小,而是char指针类型的大小(64位架构8字节,32位4字节).您应该改用 strlen(foo)

关于C通过命名管道发送分配的字符串 - linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43893077/

相关文章:

linux - crosstool-ng 无法获取 linux tarball

python - 当我以 root 身份运行我的 PyQt 应用程序时,为什么我的 QIcons 不显示在我的 QMenu 中?

python - 从 python 调用 c 程序时将数组传递给子进程模块的问题

c - 英特尔的时间戳读取 asm 代码示例是否使用了比必要的多两个寄存器?

c++ - Waf:递归收集源文件并包含路径

linux - 如何在 unix 系统上回显/打印实际文件内容

linux - 执行 'right' 时,PID 文件是否仍然存在缺陷?

linux - 在我的 Apache2 access.log 中,如何过滤显示的内容?

c++ - sscanf 麻烦吗?

c++ - JCuda全局共享内存导致错误