简体   繁体   English

如何从 shell 脚本中获取 echo 语句以及执行状态到 c++ 程序中

[英]how to get the echo statements as well as execution status from a shell script into a c++ program

I have a shell script like:我有一个 shell 脚本,例如:

#!/bin/bash
echo "my string"
return 1

And I have a c++ code where I want both the echo statement(s) as well as the exec status.我有一个 c++ 代码,我想要 echo 语句和 exec 状态。 I found some examples where we can use popen() or system() both the ways serves one requirement, but not both.我发现了一些例子,我们可以同时使用popen()system()来满足一个需求,但不能同时使用两者。 Any suggestions how to do this?任何建议如何做到这一点?

fork() + exec() would be a pretty standard way to run another executable ( please don't ever use system() , it's a security nightmare ). fork() + exec()将是运行另一个可执行文件的一种非常标准的方式(永远不要使用system() ,这是一场安全噩梦)。 To obtain the standard out / standard error stream output from the spawned process, the parent process would set up pipe s to connect to those streams and read them.要从生成的进程中获取标准输出/标准错误 stream output,父进程将设置pipe以连接到这些流并读取它们。 As for the exit code, that you can get via waitpid() once the child process terminates (you'll get a SIG_CHILD signal, so make sure you have installed a signal handler for that).至于退出代码,您可以在子进程终止后通过waitpid()获得(您将获得 SIG_CHILD 信号,因此请确保已为此安装了信号处理程序)。

I recommend a read through of Advanced Programming in the UNIX Environment, 3rd Edition .我建议通读UNIX Environment, 3rd Edition 中的高级编程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 How to get execution time and memory usage of a program (c,c++,java,python,php) in php script on ubuntu? - How to get execution time and memory usage of a program (c,c++,java,python,php) in php script on ubuntu? 使用 GDB 调试从 shell 脚本调用的 C++ 程序 - Use GDB to debug a C++ program called from a shell script 使用参数从C ++程序调用Shell脚本 - Calling a shell script from a C++ program with parameters 如何让C++程序停止求值运算语句? - How to get C++ program to stop evaluating operational statements? 从C ++程序运行Shell脚本是否会自动将Shell脚本的输出显示到控制台? - Will running a shell script from a c++ program automatically display the output of the shell script to the console? 创建C ++程序以运行Shell脚本 - Creating C++ program to run shell script 如何基于C ++ Windows对话框的程序不时获取系统状态 - How a C++ windows dialog based program to get system a status from time to time 如何从C ++代码启动的批处理/ shell脚本中获取返回代码 - How to get the return code from a batch/shell script that launched from C++ code 如何使用gdb运行程序,该程序是从Shell脚本调用的,而后者又通过boost :: process从c ++调用 - how to run a program with gdb which is invoked from a shell script, which in turn invoked from c++ via boost::process C ++程序需要来自stdin的输入,但是我想通过shell脚本管道/发送这些输入 - C++ program needs inputs from stdin, but I want to pipe/send these inputs from shell script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM