Environnement d'exploitation
CentOS 6.5
Je me demandais si je pouvais obtenir le résultat dans un programme C en exécutant une chaîne de commande shell (par exemple who) avec execl () etc.
référence http://stackoverflow.com/questions/1776632/how-to-catch-the-ouput-from-a-execl-command
J'ai essayé. Le code lié ci-dessus n'a qu'une seule ligne, mais en dessous, il essaie d'obtenir plusieurs lignes.
get_execl.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int cmd_quem(void) {
  int result;
  int pipefd[2];
  FILE *cmd_output;
  char buf[1024];
  int status;
  result = pipe(pipefd);
  if (result < 0) {
    perror("pipe");
    exit(-1);
  }
  result = fork();
  if(result < 0) {
    exit(-1);
  }
  if (result == 0) {
    dup2(pipefd[1], STDOUT_FILENO); /* Duplicate writing end to stdout */
    close(pipefd[0]);
    close(pipefd[1]);
    execl("/usr/bin/who", "who", NULL);
    _exit(1);
  }
  /* Parent process */
  close(pipefd[1]); /* Close writing end of pipe */
  cmd_output = fdopen(pipefd[0], "r");
  while(1) {
    if (feof(cmd_output)) {
      break;
    }
    if (fgets(buf, sizeof buf, cmd_output)) {
      printf("Data from who command: %s", buf);
    } else {
//      printf("No data received.\n");
    }
  }
  wait(&status);
//  printf("Child exit status = %d\n", status);
  return 0;
}
int main()
{
  cmd_quem(); 
}
résultat
% ./a.out        
Data from who command: wrf      tty1         2016-10-21 01:26 (:0)
Data from who command: wrf      pts/0        2016-10-21 01:29 (:0.0)
Data from who command: wrf      pts/1        2016-10-21 01:32 (:0.0)
qui est le résultat
% who
wrf      tty1         2016-10-21 01:26 (:0)
wrf      pts/0        2016-10-21 01:29 (:0.0)
wrf      pts/1        2016-10-21 01:32 (:0.0)
L'inconvénient est que le code est très long.
(Ajout 2016/10/21)
@ hurou927 m'a appris à utiliser popen ().
C'est beaucoup plus simple et plus facile à voir.