예를 들어, ./helloworld.sh 스크립트가 있습니다.C++에서 명령 행 실행 방법
저는 이것을 C++로 부르고 싶습니다. 어떻게해야합니까? 어떤 라이브러리를 사용할 수 있습니까?
예를 들어, ./helloworld.sh 스크립트가 있습니다.C++에서 명령 행 실행 방법
저는 이것을 C++로 부르고 싶습니다. 어떻게해야합니까? 어떤 라이브러리를 사용할 수 있습니까?
는
system("./helloworld.sh");
이 system()을 시도하려고합니다.
execxxx
functionsunistd.h
에서 C도 있습니다. 인수 관리를위한 다른 제어 레벨 중에서 프로세스를 실행하기위한 환경 변수를 지정할 수 있기 때문에 간단한 system
보다 큰 장점이 있습니다. 당신은 또한 스크립트의 출력을 얻으려면
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);
할 당신은 당신이 표준 입력을 얻을 필요가 있다면 (그리고 아무것도)
system("./helloworld.sh");
를 실행하려면/stdout 다음에 popen()을 사용해야합니다.
FILE* f = popen("./helloworld.sh","r");
적어도 두 가지 방법이 있습니다. (쉘 스크립트를 사용할 때 유닉스 계열 시스템에 관해 묻고 싶습니다).
은 첫 번째는 매우 간단하지만, (명령이 완료된 후 반환) 차단 :
/* 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.
*/
OP는 C++ 방식을 요구했기 때문에 fork/execv ...와 btw 같은 것을 언급하면 안됩니다. fork를 이미 사용하면 execv 대신 execv를 사용할 이유가 없습니까? – smerlin
그것은 ""헤더에, 또는 ""만약 당신이 좋아하면 더 나은 것을. –
mooware
''을 포함하면'std :: system'이어야합니다 - http://stackoverflow.com/questions/2900785/ –
MSalters