在网上找了一些有关linux编程程序中的<守护进程的创建>。但是大部分都未加调试就发出来,要么就是把一部分重要的东西给删除了。我最痛恨的就是在网上发做了手脚的源代码,要么你就别发,要么就发个好用的、全的。何必自己做了手脚呢?发个不好用的,大家下载学习的时候还调试不通。多浪费时间。。。。。。
下面是我修改后的源程序:
/*
*******************************************************************************
*功能:
* 后台检查邮件的程序.这个程序每个一个指定的时间回去检查我们的邮箱,
* 如果发现我们有邮件了,会不断的报警(通过机箱上的小喇叭来发出声音).然后
* 把接收到的邮件显示出来
*
*版本:V1.0
*
*运行环境:Red Hat Linux 2.6.14 [通过]
*
*小盒子
*
*******************************************************************************
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
/* Linux 的默任个人的邮箱地址是 /var/spool/mail/用户的登录名 */
#define MAILLOCAL "/var/spool/mail/user"
#define SLEEP_TIME 20
int main(int argc ,char *argv[])
{
pid_t child;
if((child = fork()) == -1) { //新建立一个子进程
printf("Fork Error:%s\n",strerror(errno)); //子进程建立失败
exit(1); //退出
}
else if (child > 0) {
while(1);
}
printf("\n*************************\n");
printf("Fork Create Successful!!!\n");
printf("*************************\n");
if(kill(getppid(),SIGTERM) == -1) { //杀掉父进程
printf("Kill Parent Error:%s\n",strerror(errno));
exit(1);
}
printf("*************************\n");
printf("The child ID number:%ld\n",getpid()); //得到子进程ID号
printf("*************************\n");
printf("Kill Parent Successful!!!\n");
printf("*************************\n");
{
int mailfd;
char MailBuffer[100]; //定义接收邮件缓冲区大小
ssize_t length; //邮件的实际长度
memset(MailBuffer,0,100); //清空邮件接收缓冲区
while(1) {
if( ( mailfd = open(MAILLOCAL,O_RDONLY) ) != -1) {
fprintf(stderr,"%s","\007"); //接收到新邮件后发出声音
length = read(mailfd,MailBuffer,100); //将新邮件存放到缓冲区里
printf("\n*************************\n");
printf("Have a new mail!!!\n");
printf("*************************\n");
printf("\n*************************\n");
printf("\nThe new mail information:\n\n");
printf("%s\n\n\n",MailBuffer);
printf("\n*************************\n");
close(mailfd);
} else {
printf("\n*************************\n");
printf("No new a mail!!!\n");
printf("*************************\n");
}
sleep(SLEEP_TIME);
}
}
}
运行结果: