在Unix C中使用管道

6

我在使用C语言处理管道时遇到了严重的问题。我的目标是从命令行获取参数(例如:./myprogram 123 45 67),将每个字符逐个读入缓冲区,将字符发送给子进程进行计数,然后将读取的字符总数返回给父进程。以下是我的代码(注意:注释是我应该完成的内容):

// Characters from command line arguments are sent to child process
// from parent process one at a time through pipe.
// Child process counts number of characters sent through pipe.
// Child process returns number of characters counted to parent process.
// Parent process prints number of characters counted by child process.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

static int toChild[2];
static int fromChild[2];
static char buffer;

int main(int argc, char **argv)
{
    int status;
    int nChars = 0;
    pid_t   pid;

    pipe(toChild);
    pipe(fromChild);

    if ((pid = fork()) == -1) {
        printf("fork error %d\n", pid);
        return -1;
    }
    else if (pid == 0) {
        close(toChild[1]);
        close(fromChild[0]);
        // Receive characters from parent process via pipe
        // one at a time, and count them.

        int count = 0;
        printf("child about to read\n");
        while(read(toChild[0], &buffer, 1)){
            count++;
        }
        // Return number of characters counted to parent process.

        write(fromChild[1], &count, sizeof(count));
        close(toChild[0]);
        close(fromChild[1]);
        printf("child exits\n");
    }
    else {
        close(toChild[0]);
        close(fromChild[1]);
        // -- running in parent process --
        printf("CS201 - Assignment 3 - Chris Gavette\n");

        write(toChild[1], &argv[1], 1); 

        // Send characters from command line arguments starting with
        // argv[1] one at a time through pipe to child process.

        read(fromChild[0], &nChars, 1);

        // Wait for child process to return. Reap child process.
        // Receive number of characters counted via the value
        // returned when the child process is reaped.
        close(toChild[1]);
        close(fromChild[0]);
        waitpid(pid, &status, 0);

        printf("child counted %d chars\n", nChars);
        printf("parent exits\n");
        return 0;
    }
}

即使我关闭了两个管道的两个端口,子进程似乎仍然挂起。


2
你在这里有两个fork调用。你知道吗?第二个盲目地覆盖了第一个返回的pid。把第一个去掉。然后考虑一下你正在执行的所有读写调用,并问问自己来回发送的东西有多大。例如:write(toChild[1], &count, 1)。嗯,countint类型;为什么你只发送一个字节而不是sizeof(count)?而且你的子循环退出条件最好还是有点问题。最后,如果你没有意识到的话,你应该为此使用两个管道描述符对,而不是一个。 - WhozCraig
啊哈,谢谢。这解决了被调用两次的问题。 - user3698112
我发现在发布这个问题一两分钟后,我需要两个文件描述符。我感觉很蠢,因为那应该是显而易见的。谢谢! - user3698112
1个回答

4

首先,这是错误的。

write(toChild[1], &count, 1) 

这最终会导致你的问题。 count 是一个 int,不是 charunsigned char。你需要发送 sizeof(count)。此外,当读取函数遇到错误时,它将返回EOF,这是非零值,因此你的子进程退出条件不正确。它应该看起来像这样:

while(read(toChild[0], &buffer, 1) == 1)

最后,您的父进程应循环遍历 argv[] 中的每个参数,并将其作为 strlen 大小的缓冲区发送。
我几乎可以确定这就是您要做的。请注意,为了保持知道哪个描述符用于特定目的的理智,我更喜欢使用 #define 来注明每个进程用于读写的内容。顺便说一下,这可以扩展到任意数量的进程,我相信这不会太远成为您下一个任务的问题:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

// P0_READ   - parent read source
// P0_WRITE  - parent write target
// P1_READ   - child read source
// P1_WRITE  - child write target

#define P0_READ     0
#define P1_WRITE    1
#define P1_READ     2
#define P0_WRITE    3
#define N_PIPES     4

int main(int argc, char **argv)
{
    int fd[N_PIPES], count = 0, i;
    pid_t pid;
    char c;

    if (pipe(fd) || pipe(fd+2))
    {
        perror("Failed to open pipe(s)");
        return EXIT_FAILURE;
    }

    // fork child process
    if ((pid = fork()) == -1)
    {
        perror("Failed to fork child process");
        return EXIT_FAILURE;
    }

    // child process
    if (pid == 0)
    {
        // close non P1 descriptors
        close(fd[P0_READ]);
        close(fd[P0_WRITE]);

        // get chars from input pipe, counting each one.
        while(read(fd[P1_READ], &c, 1) == 1)
            count++;

        printf("Child: count = %d\n", count);
        write(fd[P1_WRITE], &count, sizeof(count));

        // close remaining descriptors
        close(fd[P1_READ]);
        close(fd[P1_WRITE]);
        return EXIT_SUCCESS;
    }

    // parent process. start by closing unused descriptors
    close(fd[P1_READ]);
    close(fd[P1_WRITE]);

    // send each arg
    for (i=1; i<argc; ++i)
        write(fd[P0_WRITE], argv[i], strlen(argv[i]));

    // finished sending args
    close(fd[P0_WRITE]);

    // Wait for child process to return.
    wait(NULL);

    // wait for total count
    if (read(fd[P0_READ], &count, sizeof(count)) == sizeof(count))
        printf("Parent: count = %d\n", count);

    // close last descriptor
    close(fd[P0_READ]);

    return 0;
}

输入

./progname argOne argTwo

输出

Child: count = 12
Parent: count = 12

编辑:单管道与子进程返回状态

从原始问题的评论中看来,您的任务可能要求将子进程的返回状态收割为结果计数,而不是在管道中返回它。这样做,您可以使用一个单独的管道描述符对。我更喜欢第一种方法,但这也可以工作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

// P0_WRITE  - parent write target
// P1_READ   - child read source

#define P1_READ     0
#define P0_WRITE    1
#define N_PIPES     2

int main(int argc, char **argv)
{
    int fd[N_PIPES], count = 0;
    pid_t pid;
    char c;

    if (pipe(fd))
    {
        perror("Failed to open pipe(s)");
        return EXIT_FAILURE;
    }

    // fork child process
    pid = fork();
    if (pid == -1)
    {
        perror("Failed to fork child process");
        return EXIT_FAILURE;
    }

    if (pid == 0)
    {
        // close non P1 descriptors
        close(fd[P0_WRITE]);

        // Return number of characters counted to parent process.
        while(read(fd[P1_READ], &c, 1) == 1)
            ++count;

        close(fd[P1_READ]);
        printf("Child: count = %d\n", count);
        return count;
    }

    // parent process. start by closing unused descriptors
    close(fd[P1_READ]);

    // eacn each arg entirely
    for (int i=1; i<argc; ++i)
        write(fd[P0_WRITE], argv[i], strlen(argv[i]));

    // finished sending args
    close(fd[P0_WRITE]);

    // Wait for child process to return.
    if (wait(&count) == -1)
    {
        perror("Failed to wait for child process");
        return EXIT_FAILURE;
    }

    printf("Parent: count = %d\n", WEXITSTATUS(count));

    return 0;
}

结果是相同的,但请注意这很难调试,因为大多数调试器会信号触发你的子进程,真正的退出状态会丢失。例如,在我的Mac上,在Xcode下运行会出现错误:
Failed to wait for child process: Interrupted system call

当从命令行运行时,会得到以下结果:

Child: count = 12
Parent: count = 12

我喜欢双管方法的一个原因是它更易于理解。

哇,非常感谢!这正是我需要编程输出的内容。挂起的问题一定是由于我对读/写函数的误解造成的。我真的很感激! - user3698112
@user3698112 很高兴能帮到你。在你掌握它们之前,请尝试使用宏或符号常量来表示管道描述符对/数组的索引,这将使它们更易于阅读和编写代码。与[1][3]等相比,这个答案中发布的代码意图应该更加直观。祝你好运。 - WhozCraig
我很感激有关可读代码的建议。这是我最近一直在努力改善的事情,大多数时候,我认为我做得相当不错,但这个作业给我带来了很多麻烦,所以我只是草率地把它转化成问题形式并没有进行太多编辑。无论如何,我非常感谢你的帮助,我会尽量牢记你的建议! - user3698112
@user3698112 添加了单管道版本,我认为这可能是您任务的目标之一。它有一些注意事项,请阅读发布的评论。很高兴能帮助。 - WhozCraig
在看这个两个管道的例子时,我认为它不能用于从子进程返回值。因为如果发送端关闭,管道就无法工作,所以wait(null)应该在读取子进程到父进程的值之后。 - user3629249

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接