linux / c> link> Get the execution result of the shell command in the C program> I was taught how to use popen ()

Operating environment


CentOS 6.5

I was wondering if I could get the result in a C program by executing a shell command (eg who) string with execl () etc.

reference http://stackoverflow.com/questions/1776632/how-to-catch-the-ouput-from-a-execl-command

I've tried. The code linked above gets only one line, but below it tries to get multiple lines.

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(); 
}

result


% ./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)

who's result


% 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)

The drawback is that the code is very long.

Improved version using popen ()

(Addition 2016/10/21)

@ hurou927 taught me how to use popen ().

This is much simpler and easier to see.

Recommended Posts

linux / c> link> Get the execution result of the shell command in the C program> I was taught how to use popen ()
How to pass the execution result of a shell command in a list in Python
How to pass the execution result of a shell command in a list in Python (non-blocking version)
Measure the execution result of the program in C ++, Java, Python.
[sh] How to store the command execution result in a variable
How to output the output result of the Linux man command to a file
[Linux] How to use the echo command
How to use the Linux grep command
[Linux] Command to get a list of commands executed in the past
I want to leave an arbitrary command in the command history of Shell
How to use the C library in Python
Use the Java SDK of GoogleMapsAPI to get the result of reverse GeoCoding in Japanese.
I want to grep the execution result of strace
Linux user addition, how to use the useradd command
(Remember quickly) How to use the LINUX command line
I want to use Linux commands at the command prompt! Use Linux commands at the command prompt instead of Git Bash
[Linux] [C / C ++] Summary of how to get pid, ppid, tid
[Shell] How to get the remote default branch in Git
[Linux] [C / C ++] How to get the return address value of a function and the function name of the caller
[Linux] I tried to summarize the command of resource confirmation system
How to monitor the execution status of sqlldr with the pv command
How to get the vertex coordinates of a feature in ArcPy
Python> Comprehension> cells> I was taught how to use double comprehension / itertools
Memo of the program to get the date in two digits with javascript, Ruby, Python, shell script
I want to batch convert the result of "string" .split () in Python
[C language] How to use the crypt function on Linux [Password hashing]
I made a program to check the size of a file in Python
How to use Google Test in C
How to calculate Use% of df command
Python> set> Convert with set ()> dictionary is only key> I was taught how to convert the values of dictionary to set / dir ({}) / help ({}) / help ({} .values)
I wanted to know the number of lines in multiple files, so I tried to get it with a command
python I don't know how to get the printer name that I usually use.
I want to use Python in the environment of pyenv + pipenv on Windows 10
I made an appdo command to execute a command in the context of the app
AtCoder AGC 041 C --I was addicted to the full search of Domino Quality
A memorandum of how to execute the! Sudo magic command in Jupyter Notebook
I want to store the result of% time, %% time, etc. in an object (variable)
How to get a list of files in the same directory with python
How to get help in an interactive shell
Summary of how to use MNIST in Python
How to use the NHK program guide API
How to get the files in the [Python] folder
Use pygogo to get the log in json.
[Linux] I learned LPIC lv1 in 10 days and tried to understand the mechanism of Linux.
[For beginners] How to use say command in python!
How to get the variable name itself in python
I tried to summarize how to use matplotlib of python
How to use C216 Audio Controller on Arch Linux
[C language] [Linux] Get the value of environment variable
How to use the grep command and frequent samples
How to use the exists clause in Django's queryset
I tried to summarize how to use pandas in python
How to use the model learned in Lobe in Python
I want to use the R dataset in python
I can't use the darknet command in Google Colaboratory!
python> link> Mid-line comment in Python?> I was told that it's better to use named arguments.
I tried to rewrite the WEB server of the normal Linux programming 1st edition with C ++ 14
I made a class to get the analysis result by MeCab in ndarray with python
Ventilation is important. What I did to keep track of the C02 concentration in the room
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
I tried to create a Python script to get the value of a cell in Microsoft Excel