我正在尝试在 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);
}
结果:
如何在子级和父级(双向)中传递/查看整个消息?
最佳答案
问题是您从 buf 中读取了 20 个字符,然后添加 \0
作为第 20 个字符,最后得到该输出。您的留言
这是一条测试消息
包含更多字符。
关于无法正确读取管道中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32918673/