【问题标题】:Write some random numbers to the pipe?向管道写入一些随机数?
【发布时间】:2011-05-25 09:50:22
【问题描述】:

我的问题是我可以将整数写入管道吗?以及如何?

我需要让 3 个进程第一个生成 2 个数字,第二个对数字求和,第三个打印结果(使用管道)

谢谢大家

【问题讨论】:

  • 如果您想要更多的答案而不是“是的,write(2)”,我们将需要更多关于您正在做什么的详细信息。
  • @Zack:请参阅编辑后的问题
  • @Ignacio Vazquez-Abrams:是的
  • 家庭作业问题应标记为 |homework|。

标签: c linux operating-system pipe


【解决方案1】:

您尝试做的复杂部分是创建管道。你可以让 shell 为你做这件事......

$ ./makenumbers | ./addnumbers | ./printresult

但这很无聊,是吗?你必须有三个可执行文件。那么让我们来看看那些竖线在 C 级别上的作用。

您使用pipe 系统调用创建管道。您使用dup2 重新分配标准输入/输出。您使用fork 创建新进程,然后等待它们以waitpid 终止。设置整个事情的程序看起来像这样:

int
main(void)
{
    pid_t children[2];
    int pipe1[2], pipe2[2];
    int status;

    pipe(pipe1);
    pipe(pipe2);

    children[0] = fork();
    if (children[0] == 0)
    {
        /* in child 0 */
        dup2(pipe1[1], 1);
        generate_two_numbers_and_write_them_to_fd_1();
        _exit(0);
    }

    children[1] = fork();
    if (children[1] == 0)
    {
        /* in child 1 */
        dup2(pipe1[0], 0);
        dup2(pipe2[1], 1);
        read_two_numbers_from_fd_0_add_them_and_write_result_to_fd_1();
        _exit(0);
    }

    /* parent process still */
    dup2(pipe2[0], 0);
    read_a_number_from_fd_0_and_print_it();

    waitpid(children[0], &status, 0);
    waitpid(children[1], &status, 0);

    return 0;
}

请注意:

  • 我省略了所有错误处理,因为这会使程序的时间延长三倍。您的教师希望您加入错误处理。
  • 同样,我没有检查孩子的退出状态;你的教练也希望你检查一下。
  • 您不需要dup2 电话;您可以将管道 fd 编号传递给子例程调用。但是,如果您是 exec-ing 在孩子中使用新的二进制文件,这是更典型的,您将需要它们。然后,您还必须确保所有编号为 3 或更高的文件描述符都已关闭。
  • 我使用_exit 而不是exit 是有原因的。试着弄清楚它是什么。
  • 您需要在子进程调用的子例程中使用readwrite 而不是stdio.h 调用。原因与我使用_exit的原因有关。

【讨论】:

  • waitpid需要3个参数(pid_t pid, int *status, int options),此时第三个参数必须为0(阻塞当前进程直到子进程终止)。
【解决方案2】:

由于管道只是一个文件,您可以使用fprintf() 函数将随机数转换为文本并将其写入管道。例如:

FILE *pipe = popen("path/to/your/program", "w");
if (pipe != NULL) {
    fprintf(pipe, "%d\n", rand());
    pclose(pipe);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2012-01-28
    • 1970-01-01
    相关资源
    最近更新 更多