Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用c+运行进程+;,过滤输出,获取结果代码,获取系统错误,所有这些都在一起 我想从C++运行另一个程序,将它的输出重定向到一个文件并返回它的结果代码。 但是如果我无法运行程序(路径不正确等),我想知道_C++_Linux - Fatal编程技术网

使用c+运行进程+;,过滤输出,获取结果代码,获取系统错误,所有这些都在一起 我想从C++运行另一个程序,将它的输出重定向到一个文件并返回它的结果代码。 但是如果我无法运行程序(路径不正确等),我想知道

使用c+运行进程+;,过滤输出,获取结果代码,获取系统错误,所有这些都在一起 我想从C++运行另一个程序,将它的输出重定向到一个文件并返回它的结果代码。 但是如果我无法运行程序(路径不正确等),我想知道,c++,linux,C++,Linux,这是我的问题,我如何能:重定向一个文件,获取程序的结果代码,获取系统的错误,所有这些,一次完成 System():返回结果并易于重定向,但无法知道结果是系统错误还是应用程序结果 posix_spawn():我知道是否存在系统错误,但如何获取应用程序结果代码 请注意,我不控制已执行应用程序的代码 使用Windows很容易(抱歉…OpenProcess()函数,我需要的是linux下的OpenProcess() 谢谢您需要使用posix_spawn功能 waitpid系统调用将帮助您获取退出代码

这是我的问题,我如何能:重定向一个文件,获取程序的结果代码,获取系统的错误,所有这些,一次完成

  • System()
    :返回结果并易于重定向,但无法知道结果是系统错误还是应用程序结果
  • posix_spawn()
    :我知道是否存在系统错误,但如何获取应用程序结果代码
请注意,我不控制已执行应用程序的代码 使用Windows很容易(抱歉…
OpenProcess()
函数,我需要的是linux下的
OpenProcess()


谢谢

您需要使用
posix_spawn
功能

waitpid
系统调用将帮助您获取退出代码


您需要做的是非常匹配标准fork exec调用和文件重定向:

int pid = fork();
if( pid == -1 ) {
   // process error here
}

if( pid == 0 ) {
   int fd = open( "path/to/redirected/output", ... );
   ::close( 1 );
   dup2( fd, 1 );
   ::close( fd );
   exec...( "path to executable", ... );
   // if we are here there is a problem
   exit(123);
}
int status = 0;
waitpid( pid, &status, 0 );
// you get exit status in status
由执行官。。。我指的是exec函数系列中的一个(键入“man 3 exec”以获取信息),选择一个更适合您的函数。
如果需要重定向错误输出,请执行相同的操作,但使用描述符2。您可能需要将waitpid()放入循环中,并检查它是否被信号中断。

太好了!waitpid是我需要的函数,谢谢-我更适合Windows,并且错过了一些linux基础知识;)感谢伯尼和乔丹对我问题的更正:)
int pid = fork();
if( pid == -1 ) {
   // process error here
}

if( pid == 0 ) {
   int fd = open( "path/to/redirected/output", ... );
   ::close( 1 );
   dup2( fd, 1 );
   ::close( fd );
   exec...( "path to executable", ... );
   // if we are here there is a problem
   exit(123);
}
int status = 0;
waitpid( pid, &status, 0 );
// you get exit status in status