2014-07-15 77 views
1

我正在編寫一個測試程序,需要調用2個獨立的exe文件,等待它們完成並輸出它們的csv文件,然後讀入這些結果文件。C - 運行一個可執行文件並等待完成

我目前使用_popen創建一個管道並顯示輸出,但我並不真的需要這些,並循環,直到feof似乎毫無意義。

我想有是這樣的:

  • 我啓動我的應用程序,它在它自己的cmd窗口彈出。
  • 它調用exe1,它在自己的窗口中執行所有操作。
  • 它調用exe2,它在自己的窗口中執行所有操作。
  • 當兩者都退出時,它會繼續。

有沒有其他方法可以做到這一點?

編輯︰玩耍我發現使用System("exe1");基本上做我現在做的,但在一行。或者我在這裏錯過了什麼?

int runTest(char* testName) 
{ 
    char psBuffer[128]; 
    FILE *pPipe; 

    if ((pPipe = _popen(testName, "r")) == NULL) 
    { 
     printf("Failed to open %s", testName); 
     return 0; 
    } 

    while (fgets(psBuffer, 128, pPipe)) 
    { 
     printf(psBuffer); 
    } 

    if (feof(pPipe)) 
    { 
     printf("%s returned %d\n", testName, _pclose(pPipe)); 
     return 1; 
    } 
    else 
    { 
     printf("Error: Failed to read the pipe to the end.\n"); 
     return 0; 
    } 
} 
+1

我猜你正在使用Windows?對於Unix,您可以執行[fork](http://en.wikipedia.org/wiki/Fork_(system_call)),然後從子級執行exec,並在父級中等待相應的PID(重定向標準輸入/標準輸出孩子如果需要的話)。也許對於Windows相似的解決方案也可以,但我不能給你任何細節...... –

+0

'system(「path \\ to \\ your.exe」);'做你想做的。如果您需要可執行文件退出的退出值,請檢查'system'調用的返回值。至少這是Windows的特里... – ThoAppelsin

回答

0

您可以用線穿起來是這樣的:

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 

void*   thread_2(void *arg) 
{ 
    system("./exec2"); 
    pthread_exit(NULL); 
} 

void*   thread_1(void *arg) 
{ 
    system("./exec1"); 
    pthread_exit(NULL); 
} 

void* (*func_ptr[2])(void*) = { thread_1, thread_2 }; 

void   main() 
{ 
    pthread_t  thread_pool[2]; 

    for (int i = 0; i < 2; i++) 
    pthread_create(&thread_pool[i], NULL, func_ptr[i], NULL); 
    for (int i = 0; i < 2; i++) 
    pthread_join(thread_pool[i], NULL); 
} 

希望這會幫助你。