Search code examples
c++clinuxdaemon

shell command inside the linux daemon


I have written the daemon in C/C++ in linux. Now I want to get the out put of ls -l (list directory) command inside daemon and write output of command to the file.

I know how to write to the file from my daemon, but,

I don't know how to execute ls -l command and get the output in buffer.

Here is the code...

   /* Create a new SID for the child process */
    sid = setsid();

    if (sid < 0) {
      /* Log any failures here */

      ofs << "set sid : fail";
      ofs.close();
      exit(EXIT_FAILURE);
    }

        ofs << "\nchdir :" << chdir(filePath) << "\n";

    /* Change the current working directory */
    if ((chdir(filePath)) < 0) {
      /* Log any failures here */

      ofs << "chdir : fail";
      ofs.close();
      exit(EXIT_FAILURE);
    }

    /* Close out the standard file descriptors */
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);       

        while(1){
            //here I want to execute the ls -l and get output of the command
        }

Solution

  • You can use popen that executes a shell command and return the output as a pipe:

    #include <stdio.h>
    FILE* pipe = popen("ls -l", "r");
    if (!pipe) return "ERROR";
    

    You can also use system to execute any shell command:

    #include <stdlib.h>
    int system(const char *command);
    

    To get the output of ls -l, forward it to a file ls -l >> myls.log than read that file.

    system("ls -l >> myls.log");