与 C

如何解决与 C

我正在尝试与外部程序通信,如果执行该程序,将运行终端界面。 通常我必须提供一些输入(例如“1+1”),然后读取程序的输出(例如“2”)。 由于我需要双向通信,因此无法使用 popen()。

我的问题如下:

每当我有一部分代码要求输入时,例如包含 std::cin >> input,我都会遇到同样的问题,read 命令永远不会退出。

这里我写了一个最小的例子,子进程所做的就是读取输入并重复它。

当我尝试运行此代码时,我看到第一个打印“Parent said:”并且我可以提供输入并使用 write 发送它。但是,当我再次尝试调用 read() 函数以查看结果时,它永远不会退出。

我注意到,如果我关闭从父级到子级 (fd_p2c[1]) 的管道,那么我可以成功读取。 这显然不是我想要的,因为在我的应用程序中,我希望两个通信都保持开放。

有什么建议可以解决这个问题吗?

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

int main() {
  int status,buf_length;

  // Input and output
  char buf[256];
  char msg[256];
  char child_read[256];

  int fd_c2p[2]; // file descriptor pipe child -> parent
  int fd_p2c[2]; // file descriptor pipe parent -> child

  pipe(fd_c2p);
  pipe(fd_p2c);

  // Spawn a new process with pid
  pid_t pid = fork(); // Fork process

  if (pid == 0) {
    // Child

    // Close the unused end of the pipe
    if (close(fd_p2c[1]) != 0 || close(fd_c2p[0]) != 0) {
      fprintf(stderr,"Faild to close unused end of pipe\n");
      exit(1);
    }

    // Set the comunication
    if (dup2(fd_p2c[0],STDIN_FILENO) != 0 ||
        dup2(fd_c2p[1],STDOUT_FILENO) != 1 ||
        dup2(fd_c2p[1],STDERR_FILENO) != 2) {
      fprintf(stderr,"Faild to duplicate the end of the pipes\n");
      exit(1);
    }

    // These two pipe ends are not needed anymore
    if (close(fd_p2c[0]) != 0 || close(fd_c2p[1]) != 0) {
      fprintf(stderr,"Faild to close unused end of pipe\n");
      exit(1);
    }

    // ask kernel to deliver SIGTERM in case the parent dies
    prctl(PR_SET_PDEATHSIG,SIGTERM);

    // Moch program
    while (1) {
      fprintf(stdout,"Parent says: ");
      fflush(stdout);
      scanf("%s",child_read);
      fprintf(stdout," >> Child repeat: %s\n",child_read);
      fflush(stdout);
    }
    exit(1);
  } else {
    // Parent

    // These two pipe ends are not needed anymore
    if (close(fd_p2c[0]) != 0 || close(fd_c2p[1]) != 0) {
      fprintf(stderr,"Faild to close unused end of pipe\n");
      exit(1);
    }
  }

  // Read output and send input
  while (1) {
    // Read from child
    while (buf_length = read(fd_c2p[0],buf,sizeof(buf) - 1)) {
      buf[buf_length] = '\0';
      printf("%s",buf);
    }

    // Enter message to send
    scanf("%s",msg);
    if (strcmp(msg,"exit") == 0)
      break;

    // Send to child
    write(fd_p2c[1],msg,strlen(msg));
    //close(fd_p2c[1]);
  }

  printf("KILL");
  kill(pid,SIGKILL); // send SIGKILL signal to the child process
  waitpid(pid,&status,0);
}

解决方法

一个问题是在子进程中:

scanf("%s",child_read);

对于 %s 格式,只有三件事可以阻止 scanf 等待更多输入:

  1. 错误
  2. 文件结束
  3. 空间

假设一切正常,就不会有错误。并且由于父进程使管道保持打开状态,因此文件不会结束。而且由于父进程只写入它自己用 scanf("%s",...) 读取的内容,因此发送的数据中不会有空格。

总而言之,子进程将无限期地等待 scanf 返回,而它永远不会。

,

如果您需要双向通信,您可以使用一些 unix(7) 套接字,或者 几个 pipe(7)-s,或者一些 fifo(7)。>

您可以使用一些 JSONRPC 库。或 XDR(可能是 ONC/RPC/XDR)或 ASN/1 用于数据中心异构计算机之间的二进制通信,或 MPI。如果您可以使用一些 supercomputer,它可能具有专有库来简化在不同节点上运行的进程之间的消息传递。

考虑使用 OpenMPI

我正在尝试与外部程序通信,如果执行该程序,将运行终端界面。

也许你需要一些带有 pty(7)termios(3) ?然后从 xtermrxvt

的源代码中获取灵感

在尝试 event loop(或 poll(2)...)或 read(2)(或 recv(2) 之前,您可能需要一些 write(2) }})

您可以找到开源库(例如 send(2)Glib、...)来帮助您,您当然应该研究它们的源代码以获得灵感。

,

让我们称一个scanf("%s")能够提取的内容。 这是不是分隔符的连续字符序列(空格、制表符、换行符...)。

孩子的(重定向的)标准输入读取带有scanf("%s",child_read);单词。 当读取分隔符或到达 EOF 时,这个 单词 被称为结束。 在父级中,write(fd_p2c[1],msg,strlen(msg)); 发送一个 word(后面没有其他内容),因为 msg 在之前被提取为 word。 >

请注意,当您使用键盘输入 word 时,您还按下了 Enter 键,这会在标准输入中发送换行符。此时,终端使此行可用于 scanf()word 被称为已结束并且分隔符被忽略(在这种特定情况下,但我们可以通过 {{1 }}).

例如,如果在父级的标准输入中我们输入fgetc(), 父级获得单词 "abc\n",它按原样发送给子级。 然后孩子收到一个以 "abc" 开头但还没有结束的词:"abc" 仍在等待 scanf("%s") 之后的一些其他字符使这个词更长,或者一个分隔符或 EOF 来检测结束这个词。

例如,您可以在这个词之后发送一个分隔符。

c

或者最好依靠 // Send to child write(fd_p2c[1],strlen(msg)); char lf='\n'; write(fd_p2c[1],&lf,1); (而不是 fgets())在子级和父级中获取一行(不仅仅是一个单词)。

顺便说一下,父级中的 scanf("%s") 对我来说看起来很奇怪。 我会做这样的事情。

while/read
,

因为一般来说,我不知道消息的长度,因为我需要阅读 getValue() 表格,所以我需要创建一个外观来监听管道直到它为空。

如@some-programmer-dude 所建议的那样,有必要将 fd_c2p 添加到父文件描述符中:

O_NONBLOCK

现在,当我从文件描述符 // Parent // close unused pipe ends // These two pipe ends are not needed anymore if (close(fd_p2c[0]) != 0 || close(fd_c2p[1]) != 0) { fprintf(stderr,"Faild to close unused end of pipe\n"); exit(1); } // Add O_NONBLOCK the the fd that reads from the child int c2p_flags = fcntl(fd_c2p[0],F_GETFL); fcntl(fd_c2p[0],F_SETFL,c2p_flags | O_NONBLOCK); 中读取子级的输出时,每当我们尝试从空文件中读取时,它都会返回一个错误。 读取 fd_c2p[0] 中的错误代码应与 errno 匹配。

要知道何时停止读取 EWOULDBLOCK 需要一些有关输出的知识。 当该行的最后一个字符到达 fd_c2p[0] 且上一条消息以 EWOULDBLOCK 结束时,此特定读取应停止。

:

这个补丁解决了在程序要求输入之前不确定有多少行时从文件中读取的问题。

当消息在任何位置包含 // Read from child end_of_message = false; while (1) { buf_length = read(fd_c2p[0],buf,sizeof(buf) - 1); if (buf_length == -1) { if (end_of_message && errno == EWOULDBLOCK) break; else if (errno == EWOULDBLOCK) continue; else { fprintf(stderr,"reading from pd_c2p returned an error different " "from `EWOULDBLOCK'\n"); exit(errno); } } buf[buf_length] = '\0'; printf("%s",buf); end_of_message = buf[buf_length - 1] == ':'; } 时也应该是安全的。为了测试它,可以将不同的缓冲区减少到更小的大小(例如从 256 到 1)。

@prog-fh 还指出,原则上人们希望输入也包含空格。容纳可以使用:代替fgets

scanf

使用 // Enter message and send it over to the chid process while (fgets(msg,256,stdin) != NULL) { if (msg[strlen(msg)] == '\0') write(fd_p2c[1],strlen(msg)); else { fprintf(stderr,"Error encounter while reading input\n"); exit(1); } if (msg[strlen(msg) - 1] == '\n') break; else continue; } 的优点之一是字符串将在末尾保留换行符 fgets,这意味着一旦我们已完成阅读邮件。

然后是完整的代码

\n

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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-