programing

Linux에서 C 코드 내의 외부 프로그램을 인수로 실행하려면 어떻게 해야 합니까?

goodcopy 2022. 8. 3. 21:28
반응형

Linux에서 C 코드 내의 외부 프로그램을 인수로 실행하려면 어떻게 해야 합니까?

나는 C 코드 안에 있는 다른 프로그램을 실행하고 싶다.예를 들어 명령어를 실행하고 싶다.

./foo 1 2 3

foo같은 폴더에 존재하는 프로그램입니다.1 2 3인수입니다. fooprogram은 내 코드에 사용될 파일을 만듭니다.

이거 어떻게 해?

간단한 방법으로는system():

#include <stdlib.h>
...
int status = system("./foo 1 2 3");

system()foo가 실행이 완료될 때까지 기다린 후 상태 변수를 반환합니다(예: exitcode를 체크하는 데 사용할 수 있습니다). (명령어 종료 코드에 256을 곱하면 system()의 반환 값을 그 값으로 나누면 실제 종료 코드를 얻을 수 있습니다).int exitcode = status / 256).

(섹션 2)의 맨 페이지man 2 waitLinux 시스템에서) 상태를 검사하기 위해 사용할 수 있는 다양한 매크로를 나열합니다.가장 흥미로운 것은 다음과 같습니다.WIFEXITED그리고.WEXITSTATUS.

또는 foo의 표준 출력을 읽으려면popen(3)파일 포인터를 반환합니다( ).FILE *명령어의 표준 입출력과의 상호 작용은 파일 읽기 또는 쓰기 작업과 동일합니다.

system함수는 셸을 호출하여 명령을 실행합니다.이 방법은 편리하지만 보안에 미치는 영향은 잘 알려져 있습니다.실행할 프로그램 또는 스크립트에 대한 경로를 완전히 지정할 수 있고 플랫폼 독립성을 잃을 수 있는 경우system를 사용하면,execve에 나타낸 것과 같은 포장지exec_prog프로그램을 보다 안전하게 실행할 수 있습니다.

발신자의 인수를 지정하는 방법은 다음과 같습니다.

const char    *my_argv[64] = {"/foo/bar/baz" , "-foo" , "-bar" , NULL};

그럼 전화 주세요.exec_prog다음과 같이 기능합니다.

int rc = exec_prog(my_argv);

여기 있습니다.exec_prog기능:

static int exec_prog(const char **argv)
{
    pid_t   my_pid;
    int     status, timeout /* unused ifdef WAIT_FOR_COMPLETION */;

    if (0 == (my_pid = fork())) {
            if (-1 == execve(argv[0], (char **)argv , NULL)) {
                    perror("child process execve failed [%m]");
                    return -1;
            }
    }

#ifdef WAIT_FOR_COMPLETION
    timeout = 1000;

    while (0 == waitpid(my_pid , &status , WNOHANG)) {
            if ( --timeout < 0 ) {
                    perror("timeout");
                    return -1;
            }
            sleep(1);
    }

    printf("%s WEXITSTATUS %d WIFEXITED %d [status %d]\n",
            argv[0], WEXITSTATUS(status), WIFEXITED(status), status);

    if (1 != WIFEXITED(status) || 0 != WEXITSTATUS(status)) {
            perror("%s failed, halt system");
            return -1;
    }

#endif
    return 0;
}

에는 다음이 포함됩니다.

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

다음과 같은 파일 기술자를 통해 실행 중인 프로그램과 통신할 필요가 있는 상황에 대해서는 관련 SE 포스트를 참조하십시오.stdin그리고.stdout.

사용할 수 있습니다.fork()그리고.system()프로그램이 다음 시간까지 기다릴 필요가 없습니다.system()돌아온다.

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

int main(int argc,char* argv[]){

    int status;

    // By calling fork(), a child process will be created as a exact duplicate of the calling process.
    // Search for fork() (maybe "man fork" on Linux) for more information.
    if(fork() == 0){ 
        // Child process will return 0 from fork()
        printf("I'm the child process.\n");
        status = system("my_app");
        exit(0);
    }else{
        // Parent process will return a non-zero value from fork()
        printf("I'm the parent.\n");
    }

    printf("This is my main program and it will continue running and doing anything i want to...\n");

    return 0;
}

system()그러면 인수를 해석하고 원하는 프로그램을 실행하는 셸이 실행됩니다.프로그램을 직접 실행하려면 fork() 및 exec()을 사용합니다(이것은 셸이 명령어를 실행하기 위해 사용하는 것과 마찬가지로 system()이 셸을 실행하기 위해 사용하는 것입니다).

#include <unistd.h>

int main() {
     if (fork() == 0) {
          /*
           * fork() returns 0 to the child process
           * and the child's PID to the parent.
           */
          execl("/path/to/foo", "foo", "arg1", "arg2", "arg3", 0);
          /*
           * We woundn't still be here if execl() was successful,
           * so a non-zero exit value is appropriate.
           */
          return 1;
     }

     return 0;
}

주식회사

#include <stdlib.h>

system("./foo 1 2 3");

C++의 경우

#include <cstdlib>

std::system("./foo 1 2 3");

그런 다음 평상시와 같이 파일을 열고 읽습니다.

이렇게 하면 어떨까요?

char* cmd = "./foo 1 2 3";
system(cmd);

args가 하드코딩되지 않은 경우 변수 args로 확장하는 방법은 다음과 같습니다(이 예에서는 여전히 하드코딩되어 있지만 확장 방법을 쉽게 알아낼 수 있습니다).):

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

int argcount = 3;
const char* args[] = {"1", "2", "3"};
const char* binary_name = "mybinaryname";
char myoutput_array[5000];

sprintf(myoutput_array, "%s", binary_name);
for(int i = 0; i < argcount; ++i)
{
    strcat(myoutput_array, " ");
    strcat(myoutput_array, args[i]);
}
system(myoutput_array);

언급URL : https://stackoverflow.com/questions/5237482/how-do-i-execute-an-external-program-within-c-code-in-linux-with-arguments

반응형