将数据从一个管道传递到另一个管道



我是管道的新手,但如何将child_1的输出重定向到child_2的输入?

我正试图将值从父项传递给child_1,将1添加到该值,打印该值,然后使用该输出并将其传递给child_2,再次添加1,最后打印该值。

下面的代码对child_1有正确的输出值,但对child_2没有,如何将child_1的输出重定向到child_2的输入?

这是我到目前为止的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char * argv[]) {
int fd[2];
int PID;
pipe(fd); //fd1[0] = read | fd1[1] = write
PID = fork(); // spawn child_1
if (PID < 0){ // failed to fork
perror("Unable to fork child");
exit(1);
}

if (PID > 0) { // parent
int value = 100;

// since parent is only writing, close the reading end of pipe
close(fd[0]);
// write the data to the write end of the pipe
write(fd[1], &value,  sizeof(int));
// then close the writing end of the pipe (parent)
close(fd[1]);
/**********************************************************/
} else { // child 1
int val = 0;
// read from the parent pipe
read(fd[0], &val, sizeof(int));
val += 1;

// is this how to redirect from one pipe to another?
dup2(fd[0], fd[1]);
// this prints the right value for val (val [101] = value [100] + 1)
printf("Child [%d] read value %dn", getpid(), val);
// close the reading end of the pipe for child_1
close(fd[0]);

int PID2 = fork();  // make child 2
if(PID2 == 0) { // child 2
int val2 = 0;  
close(0); // close stdin since we are trying to take the value from child_1
// read input from child_1 pipe (NOT WORKING?)
read(fd[0], &val2, sizeof(int));
val2 += 1;
printf("Child [%d] out %dn", getpid(), val2);
close(fd[0]);
}
}
return EXIT_SUCCESS;
}

按照设置方式,不需要使用dup2()或任何其他I/O重定向。

  • #include <unistd.h>添加到包含文件列表中(并删除#include <string.h>——它似乎未使用(
  • 删除:dup2(fd[0], fd[1]);
  • 删除:close(fd[0]);
  • 删除:close(0);
  • 在第二个fork()之前,添加write(fd[1], &val, sizeof(val));

当第一个子级中有close(fd[0])时,第二个子级也会有效地关闭fd[0]

在使用结果之前,您应该检查读取和写入操作的状态。

这些变化导致:

/* SO 7383-1815 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int fd[2];
int PID;
pipe(fd);
PID = fork();
if (PID < 0)
{
perror("Unable to fork child");
exit(EXIT_FAILURE);
}
if (PID > 0)
{
int value = 100;
close(fd[0]);
write(fd[1], &value,  sizeof(int));
close(fd[1]);
}
else
{
int val = 0;
if (read(fd[0], &val, sizeof(val)) != sizeof(val))
{
perror("read() failed in child 1");
exit(EXIT_FAILURE);
}
val += 1;
printf("Child [%d] read value %dn", getpid(), val);
if (write(fd[1], &val, sizeof(val)) != sizeof(val))
{
perror("write() failed in child 1");
exit(EXIT_FAILURE);
}
int PID2 = fork();
if (PID2 == 0)
{
int val2 = 0;
if (read(fd[0], &val2, sizeof(val2)) != sizeof(val2))
{
perror("read() failed in child 2");
exit(EXIT_FAILURE);
}
val2 += 1;
printf("Child [%d] out %dn", getpid(), val2);
close(fd[0]);
close(fd[1]);
}
}
return EXIT_SUCCESS;
}

当编译时(干净地使用模糊的选项设置(,它会产生如下输出:

Child [34520] read value 101
Child [34521] out 102

我相信这就是我们想要的。

最新更新