1

我对 C++ 真的很陌生,我正在尝试从以下位置获取输出:

execv("./rdesktop",NULL);

我正在使用 C++ 和 RHEL 6 进行编程。

像 FTP 客户端一样,我想从我的外部运行程序中获取所有状态更新。有人可以告诉我我该怎么做吗?

4

2 回答 2

5

execv 替换当前进程,因此在执行后立即执行的将是您指定的任何可执行文件。

通常你做一个fork, 然后execv只在子进程中。父进程接收新子进程的 PID,它可以用来监视子进程的执行。

于 2012-03-27T20:04:08.403 回答
2

wait您可以通过调用、waitpid或来检查子进程的退出wait3状态wait4

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

int main () {
  pid_t pid = fork();
  switch(pid) {
  case 0:
    // We are the child process
    execl("/bin/ls", "ls", NULL);

    // If we get here, something is wrong.
    perror("/bin/ls");
    exit(255);
  default:
    // We are the parent process
    {
      int status;
      if( waitpid(pid, &status, 0) < 0 ) {
        perror("wait");
        exit(254);
      }
      if(WIFEXITED(status)) {
        printf("Process %d returned %d\n", pid, WEXITSTATUS(status));
        exit(WEXITSTATUS(status));
      }
      if(WIFSIGNALED(status)) {
        printf("Process %d killed: signal %d%s\n",
          pid, WTERMSIG(status),
          WCOREDUMP(status) ? " - core dumped" : "");
        exit(1);
      }
    }
  case -1:
    // fork failed
    perror("fork");
    exit(1);
  }
}
于 2012-03-27T20:03:53.547 回答