How do I execute a command and get the output of the command within C++ using POSIX?

前端 未结 11 1174
我在风中等你
我在风中等你 2020-11-21 05:39

I am looking for a way to get the output of a command when it is run from within a C++ program. I have looked at using the system() function, but that will jus

11条回答
  •  春和景丽
    2020-11-21 06:16

    You can get the output after running a script using a pipe. We use pipes when we want the output of the child process.

    int my_func() {
        char ch;
        FILE *fpipe;
        FILE *copy_fp;
        FILE *tmp;
        char *command = (char *)"/usr/bin/my_script my_arg";
        copy_fp = fopen("/tmp/output_file_path", "w");
        fpipe = (FILE *)popen(command, "r");
        if (fpipe) {
            while ((ch = fgetc(fpipe)) != EOF) {
                fputc(ch, copy_fp);
            }
        }
        else {
            if (copy_fp) {
                fprintf(copy_fp, "Sorry there was an error opening the file");
            }
        }
        pclose(fpipe);
        fclose(copy_fp);
        return 0;
    }
    

    So here is the script, which you want to run. Put it in a command variable with the arguments your script takes (nothing if no arguments). And the file where you want to capture the output of the script, put it in copy_fp.

    So the popen runs your script and puts the output in fpipe and then you can just copy everything from that to your output file.

    In this way you can capture the outputs of child processes.

    And another process is you can directly put the > operator in the command only. So if we will put everything in a file while we run the command, you won't have to copy anything.

    In that case, there isn't any need to use pipes. You can use just system, and it will run the command and put the output in that file.

    int my_func(){
        char *command = (char *)"/usr/bin/my_script my_arg > /tmp/my_putput_file";
        system(command);
        printf("everything saved in my_output_file");
        return 0;
    }
    

    You can read YoLinux Tutorial: Fork, Exec and Process control for more information.

提交回复
热议问题