这是一个特定于 Linux 的问题。
当守护程序应用程序启动时,它通常会关闭其标准流(STDOUT、STERR 和 STDIN)。
我的守护程序应用程序需要启动外部应用程序,它可能会将我需要捕获的消息打印到 STDOUT。
似乎这个子应用程序没有得到 STDOUT,因为守护进程没有。在此环境中启动外部应用程序并为其提供 STDOUT 的方法是什么?
我是否必须不关闭守护程序 STDOUT 才能让外部应用程序运行?
最佳答案
一个守护进程通过fork()创建一个子进程;子级从其父级继承所有文件描述符(不是 close-on-exec)。
如果你想让你的守护进程从 child 那里接收标准输出,你需要将它的文件描述符 1 (fileno(stdout)) 指向守护进程可以看到它的某个地方。最简单的是套接字,但您也可以使用文件。
一些代码(我还没有编译,但大致正确,应该能让你顺利上手):
// run the passed-in command in a process, returning a read file
// descriptor that will read its stdout
static int
spawn (const char * const cmd)
{
int comlink[2];
pid_t pid;
if (pipe(comlink)) {
// handle error
}
if ((pid = fork()) == -1) {
// handle error
}
if (pid == 0) {
// the child
if (dup2(comlink[1], fileno(stdout))) {
// handle error
}
close(comlink[0]);
close(comlink[1]);
execl(...); // get cmd into some exec format and put it here
_exit(-1); // should never be reached
} else {
// the parent
close(comlink[1]);
return comlink[0];
}
}
关于Daemon 可以使用 STDOUT 启动外部进程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46915920/