【发布时间】: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 << "\nFork failed"C 中没有字符指针或字符串内容的移位运算符。