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

如何解决管道似乎无法在exec覆盖的fork进程之间进行通信

我一直在尝试学习如何在IPC中使用管道,尽管我可以使用一些简单的示例,但是除了那些非常简单的程序之外,我什么也做不到。

一方面,我认为我可能存在一些比赛条件问题-我计划在管道正常运行后使信号灯正常工作-因此,如果这是问题,我很高兴得知它。

另一方面,我只是不知道我的代码在哪里掉落...

我有3个拼图:

  1. 外部流程-分叉,执行并设置管道
  2. 内部流程-执行到分叉上并将消息通过管道传递到外部
  3. 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,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],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);
}

DISPL:

#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,READ_BLOCK_SIZE);
    while (bytesRead > 0) {
        readBuffer[bytesRead] = '\0';
        printf("Display: Read %li bytes - '%s'\n",bytesRead,readBuffer);
        bytesRead = read(readFd,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] = '\0';
    strcat(readBuffer,messBuffer);
    printf("Outer: Read %li bytes\n",bytesRead);
    printf("Outer: Message Buffer: %s\n",readBuffer);
    bytesRead = read(pipeFdStr_inner[READ],READ_BLOCK_SIZE);
}
close(pipeFdStr_inner[READ]);
write(pipeFdStr_displ[WRITE],messBuffer,strlen(messBuffer));

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

bytesRead = read(pfdInnerPipe[READ],readBuffer);
    bytesRead = read(pfdInnerPipe[READ],READ_BLOCK_SIZE);
}
close(pfdInnerPipe[READ]);
write(pfdDisplPipe[WRITE],strlen(messBuffer));

通过对系统调用进行错误检查发现了问题。选中的read()报告:

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

不难看出文件描述符,并发现它不是文件描述符。

我使用了一些代码,它们在GitHub上的https://player.vimeo.com/video/111111111(堆栈溢出问题)存储库中以SOQ子目录中的文件stderr.cstderr.h的形式提供。 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,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",(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",(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],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],READ_BLOCK_SIZE);
        if (bytesRead < 0)
            err_syserr("failed to read from pipe\n");
    }
    close(pfdInnerPipe[READ]);
    write(pfdDisplPipe[WRITE],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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-