> /tmp/c...">

Get a way out of a system command in program C

Is there a better way to do this?

int numOfCPU; system("grep -c ^processor /proc/cpuinfo >> /tmp/cpuinfo"); FILE *fp = fopen("/tmp/cpuinfo", "r"); fscanf(fp, "%d", &numOfCPU); fclose(fp); system("rm /tmp/cpuinfo"); 

I do not want to create an intermediate file and then delete it.

EDIT:

This is not about reading from a file. The command can be "ls" or "echo" Hello world "

+6
source share
3 answers

Well, I was confused about the other answer. In any case, the philosophy in this answer remains the same. You can directly use the popen function.

Then you have something like this:

 int numOfCPU; FILE *fp = popen("grep -c ^processor /proc/cpuinfo", "r"); fscanf(fp, "%d", &numOfCPU); pclose(fp); 

Hope this will be helpful.

+16
source

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

You can use a pop-up call, but if you need something more flexible, such as redirecting input or safer, for example, without running a line in the shell, you should follow this example by taking pipes from the man page.

  #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int main(int argc, char *argv[]) { int pipefd[2]; pid_t cpid; char buf; if (argc != 2) { fprintf(stderr, "Usage: %s <string>\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 must modify the child process to use dup2 to redirect standard output to the pipe, and then execute the command you want to run.

+4
source

Using awk :

 #include <stdlib.h> #include <stdio.h> void main() { int numOfCPU =0; system ("awk '/processor/{numOfCPU++}END{print numOfCPU}' /proc/cpuinfo"); } 
-3
source

Source: https://habr.com/ru/post/947290/


All Articles