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

Posted

技术标签:

【中文标题】管道似乎无法在 exec() 覆盖的 fork() 进程之间进行通信【英文标题】:Pipes appear not to communicate between fork() processes overlaid by exec() 【发布时间】:2021-01-16 18:48:25 【问题描述】:

我一直在尝试学习如何为 IPC 使用管道,虽然 我可以得到一些琐碎的例子来工作,但我无法通过这些非常简单的程序来正确运行。

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

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

我有 3 个拼图:

    OUTER 进程 - 分叉、执行和设置管道 INNER 进程 - 在 fork 上执行并将消息通过管道传递给 OUTER DISPL 进程 - 执行到一个 fork 和 printf 从 OUTER 管道传输的消息

这 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] = '\0';
        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] = '\0';
        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);

【问题讨论】:

【参考方案1】:

是时候自己动手了……你有:

bytesRead = read(pipeFdStr_inner[READ], readBuffer, READ_BLOCK_SIZE);     
while (bytesRead > 0)

    readBuffer[bytesRead] = '\0';
    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));

您正在读取和写入的“文件描述符”是字符串的第一个字符,它会自动转换为int。你需要使用:

bytesRead = read(pfdInnerPipe[READ], readBuffer, READ_BLOCK_SIZE);     
while (bytesRead > 0)

    readBuffer[bytesRead] = '\0';
    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

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

我在 GitHub 上的 SOQ(堆栈溢出问题)存储库中使用了一些代码作为文件 stderr.cstderr.h 在 src/libsoq 子目录中。 outer.c 的合理完全检查版本是这样的,我也类似地错误检查了 inner.cdispl.c。请注意,我更改了程序名称,删除了 pipe_ 前缀和 .exe 后缀。此外,outer.c 会等待它的两个孩子都死了,然后才退出。

#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] = '\0';
        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

【讨论】:

你是我个人的救星!谢谢 - 这让我发疯了。非常感谢 YW。当我意识到发生了什么事时,我感到很惊讶,但是编译器并没有太多可以警告你的事情。它确实显示了错误检查的重要性。我认为与"stderr.h" 中的功能类似的一组功能对于减少错误报告的痛苦非常重要。您可能会发现相当常见的标头 &lt;err.h&gt; 中的代码反而很有用 - 例如,它在 Linux 和 macOS 上可用 - 但我更喜欢我自己的代码,它已经经过 30 多年的磨练。 你的核心代码非常好——你避免了许多常见错误,我只需要在outer.c 中将参数添加到main() 以避免警告(错误因为我使用-Werror)使用我默认的繁琐编译选项。这很不寻常——比平均水平要好得多。 干杯 - 我已经编码了很长时间,但不是在 C 中......这绝对是一种学习体验:P

以上是关于管道似乎无法在 exec() 覆盖的 fork() 进程之间进行通信的主要内容,如果未能解决你的问题,请参考以下文章

管道、分叉和​​非阻塞 IPC

如何重定向 fork() 创建的子进程的 IO 并使用 exec() 函数?

shell中sh, exec, source, fork, ./的区别

fork和exec函数

在 Ruby exec 语句中使用命名管道

使用 stdout/stderr 以外的管道与子进程通信