unix 守护进程
守护进程在Linux/Unix系统中有着广泛的应用。有时,开发人员也想把自己的程序变成守护进程。在创建一个守护进程的时候,要接触到子进程、 进程组、会晤期、信号机制、文件、目录和控制终端等多个概念。因此守护进程还是比较复杂的,在这里详细地讨论Linux/Unix的守护进程的编写,总结 出八条经验,并给出应用范例。
编程要点
1.屏蔽一些有关控制终端操作的信号。防止在守护进程没有正常运转起来时,控制终端受到干扰退出或挂起。示例如下:
signal(SIGTTOU,SIG_IGN);
signal(SIGTTIN,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
signal(SIGHUP ,SIG_IGN);
所有的信号都有自己的名字。这些名字都以“SIG”开头,只是后面有所不同。开发人员可以通过这些名字了解到系统中发生了什么事。当信号出现时,开发人员可以要求系统进行以下三种操作:
◆ 忽略信号。大多数信号都是采取这种方式进行处理的,这里就采用了这种用法。但值得注意的是对SIGKILL和SIGSTOP信号不能做忽略处理。
◆ 捕捉信号。最常见的情况就是,如果捕捉到SIGCHID信号,则表示子进程已经终止。然后可在此信号的捕捉函数中调用waitpid()函数取得该子进程 的进程ID和它的终止状态。另外,如果进程创建了临时文件,那么就要为进程终止信号SIGTERM编写一个信号捕捉函数来清除这些临时文件。
◆ 执行系统的默认动作。对绝大多数信号而言,系统的默认动作都是终止该进程。
对这些有关终端的信号,一般采用忽略处理,从而保障了终端免受干扰。
这类信号分别是,SIGTTOU(表示后台进程写控制终端)、SIGTTIN(表示后台进程读控制终端)、SIGTSTP(表示终端挂起)和SIGHUP(进程组长退出时向所有会议成员发出的)。
2.将程序进入后台执行。由于守护进程最终脱离控制终端,到后台去运行。方法是在进程中调用fork使父进程终止,让Daemon在子进程中后台执行。这就是常说的“脱壳”。子进程继续函数fork()的定义如下:
#include
#include
pid_t fork(void);
该函数是Linux/Unix编程中非常重要的函数。它被调用一次,但返回两次。这两次返回的区别是子进程的返回值为“0”,而父进程的返回值为子进程的ID。如果出错则返回“-1”。
3.脱离控制终端、登录会话和进程组。开发人员如果要摆脱它们,不受它们的影响,一般使用 setsid() 设置新会话的领头进程,并与原来的登录会话和进程组脱离。这只是其中的一种方法,也有如下处理的办法:
if ((fd = open("/dev/tty",O_RDWR)) >= 0) {
ioctl(fd,TIOCNOTTY,NULL);
close(fd);
}
其中/dev/tty是一个流设备,也是终端映射,调用close()函数将终端关闭。
4.禁止进程重新打开控制终端。进程已经成为无终端的会话组长,但它可以重新申请打开一个控制终端。开发人员可以通过不再让进程成为会话组长的方式来禁止进程重新打开控制终端,需要再次调用fork函数。
上面的程序代码表示结束第一子进程,第二子进程继续(第二子进程不再是会话组长)。
5. 关闭打开的文件描述符,并重定向标准输入、标准输出和标准错误输出的文件描述符。进程从创建它的父进程那里继承了打开的文件描述符。如果不关闭,将会浪费系统资源,引起无法预料的错误。关闭三者的代码如下:
for (fd = 0, fdtablesize = getdtablesize();
fd 0)
…… }
8.在Linux/Unix下有个syslogd的守护进程,向用户提供了syslog()系统调用。任何程序都可以通过syslog记录事件。
由于syslog非常好用和易配置,所以很多程序都使用syslog来发送它们的记录信息。一般守护进程也使用syslog向系统输出信息。 syslog有三个函数,一般只需要用syslog(...)函数,openlog()/closelog()可有可无。syslog()在 shslog.h定义如下:
#include
void syslog(int priority,char *format,...);
其中参数priority指明了进程要写入信息的等级和用途。第二个参数是一个格式串,指定了记录输出的格式。在这个串的最后需要指定一个%m,对应errno错误码。
应用范例
下面给出Linux下编程的守护进程的应用范例,在UNIX中,不同版本实现的细节可能不一致,但其实现的原则是与Linux一致的。
#include
#include
#include
main(int argc,char **argv)
{
time_t now;
int childpid,fd,fdtablesize;
int error,in,out;
/* 忽略终端 I/O信号,STOP信号 */
signal(SIGTTOU,SIG_IGN);
signal(SIGTTIN,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
signal(SIGHUP ,SIG_IGN);
/* 父进程退出,程序进入后台运行 */
if(fork()!=0) exit(1);
if(setsid()<0)exit(1);/* 创建一个新的会议组 */
/* 子进程退出,孙进程没有控制终端了 */
if(fork()!=0) exit(1);
if(chdir("/tmp")==-1)exit(1);
/* 关闭打开的文件描述符,包括标准输入、标准输出和标准错误输出 */
for (fd = 0, fdtablesize = getdtablesize(); fd < fdtablesize; fd++)
close(fd);
umask(0);/*重设文件创建掩模 */
signal(SIGCHLD,SIG_IGN);/* 忽略SIGCHLD信号 */
/*打开log系统*/
syslog(LOG_USER|LOG_INFO,"守护进程测试!\n");
while(1)
{
time(&now);
syslog(LOG_USER|LOG_INFO,"当前时间:\t%s\t\t\n",ctime(&now));
sleep(6);
}
}
此程序在Turbo Linux 4.0下编译通过。这个程序比较简单,但基本体现了守护进程的编程要点。读者针对实际应用中不同的需要,还可以做相应的调整。(
2020年10月30日 16:54
irrelevant information is sometimes required to be filled in the form which teases people to register. But now as www.signnow.com/ has coem in the market they have eliminated such steps. By this it will save time.
2021年4月20日 14:19
We provide the best professional academic writing services in UK with the help of the best professional writers. Our esteemed clients have always been satisfied with our services. We have served around 500+ clients with over a 95% project success rate.
2021年6月22日 01:27
Usefull links:
drake tax link
statistics link
helpdesk link
lawson link
planning link
free payroll link
act on link
free pos link
construction estimating link
igloo link
disk imaging link
tracking link
fax link
link reporter link
agile link development life cycle
money management link
mac antivirus link
saba link
photo management link
act-on link
clothing design link
windows backup link
link architect salary
link developer job description
hp link support
productivity link
version control link
check printing link
p2p link
case management link
vt link
link maintenance
file transfer link
healthtrust link
link raid
stata link
check point link technologies
workforce link
best vpn link
game development link
sms link
free presentation link
link quality
ticketing link
practice management link
appointment scheduling link
business management link
scada link
barcode generator link
free flowchart link
coding link
cad link free
bsa link
server link
mac link update
best home design link
pdf editing link
focus link
it link
recipe link
free 2d animation link
rendering link
2021年10月03日 05:38
https://www.digitekprinting.com/gator-board-posters is one of my trusted businesses when it comes to printing services! They even gave suggestions with the design that I want to work with what I printed with them.
2022年6月26日 19:41
very nice post, i surely adore this site, carry on it movies123
2022年8月04日 18:47
This section of the Internet is home to many of the illicit activities and websites that are available on the world wide web today. If you want to know more about how to find out what the Dark Web is and how to stay safe while surfing the web, then read on. dark web links
2022年8月04日 19:30
When the software connects to the Dark Web site, it receives a list of web addresses instead of the normal web site address. Each of these "links" is invisible to the naked eye, giving hackers a way to expose your credit card numbers, personal information, and even bank accounts. deep web
2022年8月04日 19:47
By exposing yourself to the dangers of the dark web links through unsavory websites, you will increase the likelihood that you will become the next victim of computer hackers. dark web links
2022年8月04日 20:09
By staying informed, you will be able to understand the many ways that hackers are trying to infiltrate your computer, and you can prevent them from doing their damage to your identity and your finances. By reading up on the dark web, you will be able to use the information that you find to your advantage. dark web sites
2022年8月04日 20:24
If you are visiting a legitimate website, you will not run into any problems with running into dangerous individuals. But, on the dark web, you can't really know what you are looking at. dark web
2022年8月04日 20:40
Most affiliate marketers start by creating a product to market. In this step, they should already have an idea of the product that they want to sell. The product must be one that a vast majority of people will buy, and it should be something that is easy for them to advertise. work from home jobs
2022年8月04日 20:56
The world of affiliate marketing is huge, full of new affiliates, and a whole new marketing landscape that's constantly evolving. This has resulted in affiliate marketing success stories coming out left and right this year. affiliate marketing success
2022年12月18日 20:48
In Unix-like operating systems, a daemon is a background process that performs tasks without user intervention. Daemons typically run continuously, waiting for tasks advanced rheumatology to be assigned to them, and they are often used to provide services or perform tasks that are not directly related to the user experience. Good to see the details shared here.
2023年2月17日 21:16
I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. bedroom air purifier
2023年3月10日 00:13
Thank a lot. You have done excellent job. I enjoyed your blog . Nice efforts comments clenbuterol for sale
2023年4月17日 19:40
Thank you for sharing such awesome information with us <a href="https://americasuits.com/winter-shearling-jacket/christmas-at-pemberley-manor-jessica-lowndes-coat">buy manor jessica lowndes coat</a>. Your submission is useful and the information is reliable for brand-new readers. Thanks again for sharing such a useful post.
2023年4月17日 19:42
A perfect hobby is exquisite for correct fortune. Whilst I read this it has become so interesting and also has superb material. I favored your blog. Thanks for the information and sharing.
2023年4月22日 06:28
I read a article under the same title some time ago, but this articles quality is much, much better. How you do this.. The Balkan Line Aleksandar Sreckovic Leather Jacket