【问题标题】:shell command inside the linux daemonlinux守护进程中的shell命令
【发布时间】:2015-11-09 20:44:39
【问题描述】:

我已经写了daemon in C/C++ in linux。 现在我想在守护进程中输出ls -l(列表目录)命令并将命令的输出写入文件。

我知道如何从我的守护进程写入文件,但是,

我不知道如何执行 ls -l 命令并在缓冲区中获取输出。

这里是代码...

   /* 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
        }

【问题讨论】:

  • 考虑放一些代码
  • 创建管道、fork、dup2、execve?
  • 守护进程在 bg 中运行。因此,您可以使用重定向或其他方式在文件中获取它的 o/p。
  • 这个文件可以是任何东西,甚至是你的标准输入/标准输出(终端,tty)。
  • cout &lt;&lt; "\nFork failed" C 中没有字符指针或字符串内容的移位运算符。

标签: c++ c linux daemon


【解决方案1】:

您可以使用popen 执行shell 命令并将输出作为管道返回:

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

你也可以使用system来执行任何shell命令:

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

要获得ls -l 的输出,请将其转发到文件ls -l &gt;&gt; myls.log,而不是读取该文件。

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

【讨论】:

  • 所以为了每次都得到输出我应该重定向到文件然后只从文件中读取?我不能把它放在缓冲区而不是写入文件吗?
  • 您可以使用popen 将输出作为文件返回。答案已更新
  • 牛眼... :)...这(popen())是我想要的东西...完美的链接...非常感谢:)...我接受你的帮助...... :)......还有投票......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 1970-01-01
相关资源
最近更新 更多