2012-03-27 211 views
1

我真的很新的C++,我想從輸出:如何獲得execv的返回值?

execv("./rdesktop",NULL); 

我編程在C++和RHEL 6

就像一個FTP客戶端,我想獲得的所有狀態從我的外部運行程序更新。有人能告訴我我該怎麼做?

+3

返回值(例如exit()或類似的結果)或輸出(即stdout/stderr)?你的問題標題指出了一件事,但你的問題是另一個:-) – 2012-03-27 20:03:07

+5

我不確定你瞭解'execv'的作用;它**用指定的過程替換**你的過程。你的過程不再存在,所以沒有什麼可做的捕獲! – 2012-03-27 20:03:13

+2

'execv'只在失敗的情況下返回。 – 2012-03-27 20:05:35

回答

1

您可以通過調用waitwaitpid,wait3wait4來檢查子進程的退出狀態。

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

execv取代當前進程,執行它是怎麼執行會在你指定的任何可執行經過這麼立即。

通常情況下,您只需在子進程中執行fork,然後再執行execv。父進程接收新孩子的PID,它可以用來監視孩子的執行情況。