2010-07-07 40 views

回答

10

嘗試

system("./helloworld.sh"); 
+2

這是在「」頭或「」如果你喜歡這更好的。 – mooware 2010-07-07 21:34:05

+0

當你包含''時,它應該是'std :: system' - 參見http://stackoverflow.com/questions/2900785/ – MSalters 2010-07-08 13:46:14

1

在C中還有execxxx functionsunistd.h。與簡單的system相比,它們有很大的優勢,因爲您可以指定要在進程參數管理的其他控制級別中運行的進程的環境變量。

+0

儘管沒有Cygwin,但在Windows上不起作用。 – 2010-07-07 21:33:51

+4

他願意用Windows下的bash sh文件做什麼? :-) – jdehaan 2010-07-07 21:35:41

+1

你也會失去對C++程序的控制嗎?如果我記得,exec永遠不會回來。 – KLee1 2010-07-07 21:35:59

0

,如果你也想拿到劇本的輸出做

char fbuf[256]; 
char ret[2555]; 
FILE *fh; 
if ((fh = popen("./helloworld.sh", "r")) == NULL) { 
    return 0; 
}else{ 
    while (fgets(fbuf, sizeof(fbuf), fh)) { 
    strcat(ret, fbuf);    
    }   
} 
pclose(fh); 
5

如果你只是想如果你需要獲得標準輸入來運行它(沒有別的)

system("./helloworld.sh"); 

/stdout那麼你需要使用popen()

FILE* f = popen("./helloworld.sh","r"); 
1

至少有兩種可能的方法。 (我想你在問使用shell腳本的類Unix系統)

第一個是非常簡單的,但是阻塞(它返回的命令已經完成後):

/* Example in pure C++ */ 
#include <cstdlib> 
int ret = std::system("/home/<user>/helloworld.sh"); 

/* Example in C/C++ */ 
#include <stdlib.h> 
int ret = system("/home/<user>/helloworld.sh"); 

的第二種方式是不容易,但可能是無阻塞(腳本可以作爲運行並行處理):

/* Example in C/C++ */ 
#include <unistd.h> 
pid_t fork(void); 
int execv(const char *path, char *const argv[]); 

/* You have to fork process first. Search for it, if you don't know how to do it. 
* In child process you have to execute shell (eg. /bin/sh) with one of these 
* exec* functions and you have to pass path-to-your-script as the argument. 
* If you want to get script output (stdout) on-the-fly, you can do that with 
* pipes. Just create the reading pipe in parent process before forking 
* the process and redirect stdout to the writing pipe in the child process. 
* Then you can just use read() function to read the output whenever you want. 
*/ 
+0

由於OP要求採用C++方式,所以不應該提及像fork/execv ...和btw這樣的東西,當您已經使用fork時,沒有理由使用execv而不是execv,還是存在? – smerlin 2010-07-07 22:51:27