[英]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.