无法正确读取管道中的值

标签 c cygwin pipe fork

我正在尝试在 C 中启动一个简单的管道(使用 CygWin 和 Dev-C++)以在父项和单个子项之间传递值。这是 parent 代码 (pipesnd.c):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int FIFO[2];
    char *msg = "This is a test message";
    char str[10];



    if (pipe(FIFO) == -1)
    {
        printf("cannot create pipe\n");
        exit(1);
    }
    write(FIFO[1], msg, strlen(msg));

    sprintf(str, "%d", FIFO[0]);
    printf("I am the parent and this was in the pipe: %s \n", str);
    fflush(stdout);




    switch (fork())
    {
    case 0:
        execl("c:/Dev-Cpp/Lift 2/pipercv", "pipercv", str, NULL);  
        exit(1);
    case -1:
        perror("fork() failed:");
        exit(2);
    default:

    }






    exit(0);
}

代码(pipercv.c):

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define NBUF 100
int main(int argc, char *argv[])
{
    int fd;
    char buf[NBUF];
    if (argc != 2)
    {
        printf("expect pipercv fd\n");
        exit(1);
    }
    fd = atoi(argv[1]);


    read(fd, buf, 20);
    buf[20] = '\0';
    printf("I am the child and this was in the pipe: %s \n", buf);
    fflush(stdout);
    sleep(10);

}

结果:

enter image description here

如何在子级和父级(双向)中传递/查看整个消息?

最佳答案

问题是您从 buf 中读取了 20 个字符,然后添加 \0 作为第 20 个字符,最后得到该输出。您的留言 这是一条测试消息 包含更多字符。

关于无法正确读取管道中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32918673/

相关文章:

c++ - 如何在 Cygwin 中禁用由 g++ 生成的扩展 .exe?

c++ - 如何使用 Cygwin 构建 Google RE2?

linux - bash 标准输出无法重定向到文件

node.js - 在单个 block 上执行管道操作(node-wav)

java - 运行java管道到mutt

c - 结构声明中的结构数组 : "array type has incomplete element type"

c - 构造变量后使其成为常量

c - 如何通过ProcessID查找进程?

c - 为什么 a = 6 在一大堆运算中不把 6 赋值给 a 呢? (C语言编程)

windows - 无法从 Windows 命令提示符运行 curl 命令,但可以从 cygwin 驱动器运行它