管道似乎无法在由 exec() 覆盖的 fork() 进程之间进行通信

Pipes appear not to communicate between fork() processes overlaid by exec()

我一直在努力学习如何使用 IPC 管道,虽然 我可以使用简单的示例,但除了那些非常简单的程序,我什么都学不会正确行事。

一方面,我想我可能有一些竞争条件问题 - 我计划在管道工作后让信号量工作 - 所以如果这是问题所在,我'我很高兴听到这个消息。

另一方面,我只是不知道我的代码哪里出错了...

这个拼图我有 3 块:

  1. 外部进程 - 分叉、执行和设置管道
  2. INNER 进程 - 执行到 fork 上并将消息通过管道传递给 OUTER
  3. DISPL 进程 - 执行到叉子上并打印从 OUTER
  4. 传输的消息

这 3 个进程分叉并执行得很好,我只是从来没有从 INNER 管道中读取任何内容,这导致消息缓冲区包含一个空字符串。因此,DISPL 从不显示任何内容。

我希望 DISPL 能够显示每个 9 个字符的块及其包含的内容。没有读取缓冲区的组合以获得漂亮的打印,因为无论如何我在那个时候什么也得不到。

我的问题是,为什么这些管道不传输任何数据?

一如既往,我们很乐意接受所有帮助。

外部:

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

#define READ 0
#define WRITE 1
#define READ_BLOCK_SIZE 9

#define PROCESS_COUNT 2
#define SLEEP_TIME 2

int pfdInnerPipe[2];
int pfdDisplPipe[2];

int main()
{
    pid_t processID;
    char readBuffer[READ_BLOCK_SIZE+1];

    ssize_t bytesRead;
    char pipeFdStr_inner[10];
    char pipeFdStr_displ[10];

    if (pipe(pfdInnerPipe) < 0 || pipe(pfdDisplPipe) < 0)   exit(1);

    sprintf(pipeFdStr_inner, "%d", pfdInnerPipe[WRITE]);
    sprintf(pipeFdStr_displ, "%d", pfdDisplPipe[READ]);

    for (int count = 0; count < PROCESS_COUNT; count++)
    {
        processID = fork();
        switch (processID)
        {
            case 0:
                if (count == 0) // spawn inner
                {
                    // Inner will only write to pipe 1
                    close(pfdInnerPipe[READ]);
                    close(pfdDisplPipe[WRITE]);
                    close(pfdDisplPipe[READ]);
                    execl("./pipe_inner.exe", "pipe_inner.exe", pipeFdStr_inner, (char *)NULL); 
                    exit(2);
                } else if (count == 1) // spawn display
                {
                    // Display will only read from display pipe
                    close(pfdDisplPipe[WRITE]);
                    close(pfdInnerPipe[WRITE]);
                    close(pfdInnerPipe[READ]);
                    execl("./pipe_displ.exe", "pipe_displ.exe", pipeFdStr_displ, (char *)NULL); 
                    exit(2);
                }
                break;
            case -1:
                perror("fork failed");
                exit(3);
                break;
            default :
                continue;
        }
    }
    // parent process
    // parent will only read from INNER pipe and write to DISPL pipe
    close(pfdDisplPipe[READ]);
    close(pfdInnerPipe[WRITE]);
    sleep(SLEEP_TIME); // allow time for something to be on the pipe
    char messBuffer[] = "";
    bytesRead = read(pipeFdStr_inner[READ], readBuffer, READ_BLOCK_SIZE);     
    while (bytesRead > 0)
    {
        readBuffer[bytesRead] = '[=10=]';
        strcat(readBuffer, messBuffer);
        printf("Outer: Read %li bytes\n", bytesRead);
        printf("Outer: Message Buffer: %s\n", readBuffer);
        bytesRead = read(pipeFdStr_inner[READ], readBuffer, READ_BLOCK_SIZE);
    }
    close(pipeFdStr_inner[READ]);
    write(pipeFdStr_displ[WRITE], messBuffer, strlen(messBuffer));
    sleep(SLEEP_TIME); // keep the pipe open to read from
    close(pipeFdStr_displ[WRITE]);
}

内部:

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

#define READ_BLOCK_SIZE 9
#define SLEEP_TIME 10

int main(int argc, char *argv[])
{
    int writeFd;
    char *strFromChild = "Message from INNER to OUTER";
    if(argc != 2) {
        exit(1);
    }
    writeFd = atoi(argv[1]);
    write(writeFd, strFromChild, strlen(strFromChild));
    sleep(SLEEP_TIME); // keep pipe open for a while
    close(writeFd);
}

显示:

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

#define READ_BLOCK_SIZE 9
#define SLEEP_TIME 5

int main(int argc, char *argv[])
{
    int readFd;
    char readBuffer[READ_BLOCK_SIZE+1];
    ssize_t bytesRead;
    if(argc != 2) {
        exit(1);
    }
    readFd = atoi(argv[1]);
    sleep(SLEEP_TIME); // allow time for everything else to happen
    bytesRead = read(readFd, readBuffer, READ_BLOCK_SIZE);
    while (bytesRead > 0) {
        readBuffer[bytesRead] = '[=12=]';
        printf("Display: Read %li bytes - '%s'\n", bytesRead, readBuffer);
        bytesRead = read(readFd, readBuffer, READ_BLOCK_SIZE);
    }
    printf("Display: Finished reading from pipe 2\n");
    close(readFd);
}

是时候踢自己了……你有:

bytesRead = read(pipeFdStr_inner[READ], readBuffer, READ_BLOCK_SIZE);     
while (bytesRead > 0)
{
    readBuffer[bytesRead] = '[=10=]';
    strcat(readBuffer, messBuffer);
    printf("Outer: Read %li bytes\n", bytesRead);
    printf("Outer: Message Buffer: %s\n", readBuffer);
    bytesRead = read(pipeFdStr_inner[READ], readBuffer, READ_BLOCK_SIZE);
}
close(pipeFdStr_inner[READ]);
write(pipeFdStr_displ[WRITE], messBuffer, strlen(messBuffer));

您正在读取和写入的 'file descriptors' 是字符串的第一个字符,它会自动转换为 int。您需要使用:

bytesRead = read(pfdInnerPipe[READ], readBuffer, READ_BLOCK_SIZE);     
while (bytesRead > 0)
{
    readBuffer[bytesRead] = '[=11=]';
    strcat(readBuffer, messBuffer);
    printf("Outer: Read %li bytes\n", bytesRead);
    printf("Outer: Message Buffer: %s\n", readBuffer);
    bytesRead = read(pfdInnerPipe[READ], readBuffer, READ_BLOCK_SIZE);
}
close(pfdInnerPipe[READ]);
write(pfdDisplPipe[WRITE], messBuffer, strlen(messBuffer));

问题是通过检查系统调用的错误发现的。检查的 read() 报告:

outer: 2020-09-30 23:15:48.086 - pid=36674: failed to read from pipe
error (9) Bad file descriptor

不难仔细查看文件描述符,发现它不是文件描述符。

我使用了我的 SOQ (Stack Overflow Questions) repository on GitHub as files stderr.c and stderr.h in the src/libsoq sub-directory 中可用的一些代码。 outer.c的合理全检版本是这样的,我也同样错误检查了inner.cdispl.c。请注意,我更改了程序名称,删除了 pipe_ 前缀和 .exe 后缀。此外,outer.c 在退出之前等待它的 children 死亡。

#include "stderr.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

#define READ 0
#define WRITE 1
#define READ_BLOCK_SIZE 9

#define PROCESS_COUNT 2
#define SLEEP_TIME 2

int pfdInnerPipe[2];
int pfdDisplPipe[2];

int main(int argc, char **argv)
{
    if (argc > 0)
        err_setarg0(argv[0]);
    err_setlogopts(ERR_PID | ERR_MILLI);
    pid_t processID;
    char readBuffer[READ_BLOCK_SIZE + 1];

    ssize_t bytesRead;
    char pipeFdStr_inner[10];
    char pipeFdStr_displ[10];

    if (pipe(pfdInnerPipe) < 0 || pipe(pfdDisplPipe) < 0)
        exit(1);

    err_remark("inner (%d,%d), displ (%d,%d)\n",
                pfdInnerPipe[READ], pfdInnerPipe[WRITE],
                pfdDisplPipe[READ], pfdDisplPipe[WRITE]);
    sprintf(pipeFdStr_inner, "%d", pfdInnerPipe[WRITE]);
    sprintf(pipeFdStr_displ, "%d", pfdDisplPipe[READ]);

    for (int count = 0; count < PROCESS_COUNT; count++)
    {
        processID = fork();
        switch (processID)
        {
        case 0:
            if (count == 0)     // spawn inner
            {
                // Inner will only write to pipe 1
                close(pfdInnerPipe[READ]);
                close(pfdDisplPipe[WRITE]);
                close(pfdDisplPipe[READ]);
                // execl("./pipe_inner.exe", "pipe_inner.exe", pipeFdStr_inner, (char *)NULL);
                execl("./inner", "inner", pipeFdStr_inner, (char *)NULL);

                err_syserr("failed to execute ./inner");
                exit(2);
            }
            else if (count == 1)       // spawn display
            {
                // Display will only read from display pipe
                close(pfdDisplPipe[WRITE]);
                close(pfdInnerPipe[WRITE]);
                close(pfdInnerPipe[READ]);
                // execl("./pipe_displ.exe", "pipe_displ.exe", pipeFdStr_displ, (char *)NULL);
                execl("./displ", "displ", pipeFdStr_displ, (char *)NULL);
                err_syserr("failed to execute ./displ");
                exit(2);
            }
            break;
        case -1:
            perror("fork failed");
            exit(3);
            break;
        default:
            err_remark("forked %d\n", processID);
            continue;
        }
    }

    // parent process
    // parent will only read from INNER pipe and write to DISPL pipe
    close(pfdDisplPipe[READ]);
    close(pfdInnerPipe[WRITE]);
    sleep(SLEEP_TIME); // allow time for something to be on the pipe
    char messBuffer[] = "";
    bytesRead = read(pfdInnerPipe[READ], readBuffer, READ_BLOCK_SIZE);
    if (bytesRead < 0)
        err_syserr("failed to read from pipe\n");
    err_remark("read %zd bytes [[%.*s]]\n", bytesRead, (int)bytesRead, readBuffer);
    while (bytesRead > 0)
    {
        readBuffer[bytesRead] = '[=13=]';
        strcat(readBuffer, messBuffer);
        printf("Outer: Read %li bytes\n", bytesRead);
        printf("Outer: Message Buffer: %s\n", readBuffer);
        bytesRead = read(pfdInnerPipe[READ], readBuffer, READ_BLOCK_SIZE);
        if (bytesRead < 0)
            err_syserr("failed to read from pipe\n");
    }
    close(pfdInnerPipe[READ]);
    write(pfdDisplPipe[WRITE], messBuffer, strlen(messBuffer));
    sleep(SLEEP_TIME); // keep the pipe open to read from
    close(pfdDisplPipe[WRITE]);
    int status;
    int corpse;
    while ((corpse = wait(&status)) > 0)
        err_remark("child %d exited with status 0x%.4X\n", corpse, status);
    err_remark("exits\n");
    return 0;
}

示例输出:

outer: 2020-09-30 23:26:24.222 - pid=36852: inner (3,4), displ (5,6)
outer: 2020-09-30 23:26:24.224 - pid=36852: forked 36853
outer: 2020-09-30 23:26:24.224 - pid=36852: forked 36854
inner: 2020-09-30 23:26:24.437 - pid=36853: fd = 4
displ: 2020-09-30 23:26:24.590 - pid=36854: fd = 5
outer: 2020-09-30 23:26:26.226 - pid=36852: read 9 bytes [[Message f]]
Outer: Read 9 bytes
Outer: Message Buffer: Message f
Outer: Read 9 bytes
Outer: Message Buffer: rom INNER
Outer: Read 9 bytes
Outer: Message Buffer:  to OUTER
inner: 2020-09-30 23:26:34.441 - pid=36853: exiting
outer: 2020-09-30 23:26:36.441 - pid=36852: child 36853 exited with status 0x0000
Display: Finished reading from pipe 2
displ: 2020-09-30 23:26:36.441 - pid=36854: exiting
outer: 2020-09-30 23:26:36.442 - pid=36852: child 36854 exited with status 0x0000
outer: 2020-09-30 23:26:36.442 - pid=36852: exits