繁体   English   中英

如何获得execv的返回值?

[英]How do I get the return value of a execv?

我真的是C ++的新手,我正在尝试从以下命令获取输出:

execv("./rdesktop",NULL);

我正在C ++和RHEL 6上编程。

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

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

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

您可以通过调用waitwaitpidwait3wait4来检查子进程的退出状态。

#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);
  }
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM