转:https://blog.csdn.net/hoi0714/article/details/7349129
通过命令ps -e -o pid,ppid,cmd,tty可以看出但凡daemon进程,其tty都显示为?,也就是不存在tty
1629 1 /usr/sbin/sshd ?
1684 1 /usr/sbin/boa ?
————————————————
/*
* 判断进程是否为daemon进程
* /dev/tty可以打开的为前台程序, 不可打开的为daemon
* @return: true, daemon; false, 非daemon
* */
bool is_daemon(void)
{
int fd = -1;
fd = open("/dev/tty", O_RDWR);
if(fd < 0)
return true;
close(fd);
return false;
在一个daemon里,如果你用了exec,那么exec的进程也是一个daemon
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t pid;
pid = fork();
if(pid < 0){
perror("fail to fork");
exit(1);
}else if(pid == 0){
setsid();
chdir("/");
umask(0);
int fd = getdtablesize();
int i;
for(i=0; i<fd; i++){
close(i);
}
}
else{
exit(1);
}
execl("/home/linux/app/app/daemon/andy_app","andy_app",(char *)0);
system("echo 444 > /tmp/test.txt");
for(;1;){
}
return 0;
执行ps -e -o pid,ppid,cmd,tty,pcpu
pid ppid cmd tty cpu%
8182 2037 andy_app ? 0.0