gpt4 book ai didi

c++ - linux守护进程中的shell命令

转载 作者:太空狗 更新时间:2023-10-29 12:14:02 26 4
gpt4 key购买 nike

我已经在 linux 中用 C/C++ 编写了 daemon。现在我想在守护进程中获取 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
}

最佳答案

您可以使用 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 >> myls.log,然后读取该文件。

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

关于c++ - linux守护进程中的shell命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32046563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com