[英]Does closing the descriptor affect the daemon process created
I wanna create a daemon process, which runs the top
command of Linux in the background. 我想创建一个守护进程,该进程在后台运行Linux的
top
命令。 If I closed all the descriptor, I can't find that top
was created, because there is nothing about top
when I use the ps -aux
command to check. 如果我关闭了所有的描述,我无法找到
top
的创建,因为没有什么关于top
,当我使用ps -aux
命令检查。 If I removed the lines about closing the descriptor, the top
will run at terminal. 如果删除有关关闭描述符的行,则
top
将在终端运行。
What's wrong with my code? 我的代码有什么问题? If I wanna the program run correctly when closing the descriptor, what should I do?
如果我想在关闭描述符时使程序正常运行,该怎么办?
This is the code. 这是代码。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
void main(void)
{
int pid;
int i;
int fd;
char *d[2];
char a[5] = "top";
d[0] = a;
a[3] = '\0';
d[1] = NULL;
signal(SIGCHLD, SIG_IGN);
if ((pid = fork()) == -1)
perror("fork error");
else if (pid > 0)
exit(0);
else {
setsid();
if ((pid = fork()) == -1)
perror("fork error");
else if (pid > 0)
exit(0);
else {
for (i = 0;i < 255;i++)
close(i);
fd = open("/dev/null", O_RDWR);
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
close(fd);
chdir("/");
umask(0);
printf("%s\n", d[0]);
execvp(d[0], d);
perror("execvp failed");
exit(1);
}
}
}
I think I find the stupid mistake I have made.I close all the descriptors and point the stdin,stdout,stdout to /dev/null.But the top command need the system information coming from the input.So the execvp faild, the top command doesn't execute. 我想我发现自己犯了一个愚蠢的错误。我关闭所有描述符并将stdin,stdout,stdout指向/ dev / null。但是top命令需要来自输入的系统信息。因此execvp失败了,top命令不执行。
If I don't close the descriptor 0 (stdin), the top command will execute in the background.If I close the descriptor 0 and point the descriptor 2 (stderr)to a log, the error will be print in the log. 如果我不关闭描述符0(stdin),则top命令将在后台执行;如果我关闭描述符0并将描述符2(stderr)指向日志,则会在日志中打印错误。
It is too stubborn to think that the daemon process must close all descripotrs first .In case of wasting resource, we should just close the unecessary descripotrs. 认为守护程序进程必须先关闭所有描述符是太固执了。如果浪费资源,我们应该只关闭不必要的描述符。
From the top manpage: "-b :Batch-mode operation Starts top in 'Batch' mode, which could be useful for sending output from top to other programs or to a file. In this mode, top will not accept input" 从顶部的联机帮助页开始:“ -b:批处理模式操作以'批处理'模式启动top,这对于从top向其他程序或文件发送输出很有用。在这种模式下,top将不接受输入。
The top command can execute without input ,using argument -b, and this works in my code . 使用参数-b,无需输入即可执行top命令,这在我的代码中有效。
Thanks very much. 非常感谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.