Get system command output in C program

后端 未结 3 1941
误落风尘
误落风尘 2020-12-30 10:17

Is there a better way to do it?

int numOfCPU;
system(\"grep -c ^processor /proc/cpuinfo >> /tmp/cpuinfo\");
FILE *fp = fopen(\"/tmp/cpuinfo\", \"r\");
         


        
3条回答
  •  说谎
    说谎 (楼主)
    2020-12-30 10:33

    You need to use redirection and pipes to do what you are trying to do.

    The popen call can help you, but if you want something more flexible, such as also redirecting input, or more secure, such as not running a string in the shell, you should follow this example, taking from the manual page of pipe.

       #include 
       #include 
       #include 
       #include 
       #include 
    
       int
       main(int argc, char *argv[])
       {
           int pipefd[2];
           pid_t cpid;
           char buf;
    
           if (argc != 2) {
            fprintf(stderr, "Usage: %s \n", argv[0]);
            exit(EXIT_FAILURE);
           }
           if (pipe(pipefd) == -1) {
               perror("pipe");
               exit(EXIT_FAILURE);
           }
    
           cpid = fork();
           if (cpid == -1) {
               perror("fork");
               exit(EXIT_FAILURE);
           }
    
           if (cpid == 0) {    /* Child reads from pipe */
               close(pipefd[1]);          /* Close unused write end */
    
               while (read(pipefd[0], &buf, 1) > 0)
                   write(STDOUT_FILENO, &buf, 1);
    
               write(STDOUT_FILENO, "\n", 1);
               close(pipefd[0]);
               _exit(EXIT_SUCCESS);
    
           } else {            /* Parent writes argv[1] to pipe */
               close(pipefd[0]);          /* Close unused read end */
               write(pipefd[1], argv[1], strlen(argv[1]));
               close(pipefd[1]);          /* Reader will see EOF */
               wait(NULL);                /* Wait for child */
               exit(EXIT_SUCCESS);
           }
        }
    

    You should modify the child process to use dup2 to redirect the standard output to the pipe and then exec the command you want it to run.

提交回复
热议问题