Linux ———— daemons and Crond timed tasks

Source: Internet
Author: User
Tags session id

I. Daemon process

Daemons, also known as the wizard (Daemon) process, as the name implies, the Guardian is always there, it is running in the background of a special process, independent of the control terminal and periodically perform certain tasks or wait to handle certain occurrences of the event. For example, when the Linux system starts, it starts some system service processes, because these processes do not control the terminal and therefore cannot directly interact with the user, its life cycle with the system, rather than the user log on or run the program to start the process is completed or the user logs off after the termination, this process is called daemons or daemon processes.

The daemons in the system can be viewed under the terminal, which usually ends with the first letter D of the wizard's Word daemon:


650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7F/ED/wKioL1cx3APSbqWKAAAoOHiXxvs283.png "title=" Daemon. png "alt=" Wkiol1cx3apsbqwkaaaoohixxvs283.png "/>


As can be seen from the above, the process ID number, process group ID and session ID of most processes are the same ID number, and its control terminal TTY is not, therefore, the daemon has the following characteristics:

    1. The daemon processes itself into a process group and is self-contained, that is, the process group in which the Daemon resides and the session itself;

    2. Daemons are not associated with terminal devices;


Two. Creating daemons

We can create a daemon ourselves using the features of the daemon, and the function used is the SETSID function:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/7F/ED/wKioL1cx4y2idsKEAABp5COahVg247.png "title=" Setsid.png "alt=" Wkiol1cx4y2idskeaabp5coahvg247.png "/>

The function's argument is null, and the return value is pid_t, which is the process ID number that called the function;

The SETSID function call has the following three features:

    1. A new session is created and the function process is called the session first process, and the session ID is the process ID;

    2. A new process group is created and the function process is called a process group leader process, and the process ID is the process IDs;

    3. If the call function process and a control Terminal association, then lose the terminal, the terminal will still exist and can read and write, but only a file and no longer a control terminal;

It is important to emphasize that the calling function process is not a leader process before calling Setsid , so you might consider using fork to create a child process to call Setsid, because there are processes before the same process group is a neutron process. The team leader process is the first process in the group, so you can determine that the child process is not the leader process.


There are generally several steps to creating a daemon:

    1. Call Umask to set the file mode creation mask to 0 to ensure that the party process wants to generate files that are not controlled by system permissions;

    2. Call Fork to create a child process to ensure that the child process is not the leader process, while leaving the parent process to leave only the child process;

    3. Call the Setsid function, which creates a new session and a process group, the process group ID and the session ID are the ID of the child process, while the child process loses its original linked control terminal (fork again, so that the current child process exits, Because the current child process is the beginning of the session may also open the control terminal, and the sub-process again fork is not the first session, ensure that the control terminal will not be opened again;

    4. Changes the current user directory to the root directory, making the process working directory stable;

    5. Turn off the unwanted file descriptor;

    6. Other (ignoring sigchild signals);


Programming:

#include  <stdio.h> #include  <signal.h> #include  <unistd.h> #include  < Stdlib.h>void my_daemon () {    umask (0);//Set File creation screen word for 0    pid_t  pid;    pid = fork ();//Create Child process     if (pid <  0)     {           printf (" First fork failed...\n ");         perror (" fork ");     }       else if (pid > 0)//father     Parent Process exits     {           printf (" Father process out...pid: %u\n ",  getpid ());         exit (0);    }       //child    Sub-process     printF ("child process...pid: %u\n",  getpid ());     if ((Pid = setsid ()) &NBSP;&LT;&NBSP;0)//Call setsid function to create daemon         perror ("Setsid");     else        printf ("create daemon process  success...pid: %u\n ",  getpid ());     if ((Pid = fork ())  <  0)//fork again and leave the parent process, making sure that the child process is not the first session no longer opens the TTY device     {            printf ("second fork failed...\n");         perror ("fork");     }       else if (PID &NBSP;&GT;&NBSP;0)//father    Parent Process Exit     {            printf ("last child as father process out...pid: %u \ n ",  getpid ());        exit (1);     }    if ( ChDir ("/")  < 0)//change the working directory to the root directory     {         printf ("change dir failed...\n");         perror ("ChDir ");     }    printf (" signal: %u\n ",  signal (SIGCHLD, SIG_ IGN));     if (Close (0)  < 0)//switch off standard input          printf ("close stdin failed...\n");     if (Close (2)  < 0)// Switch off the standard output         printf ("close stderr failed...\n");     if (Close (1)  < 0)//Turn off standard error         printf ( "close stdout failed...\n");} Int main () {    my_daemon ();     while (1);      return 0;} 


To run the program:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7F/FE/wKioL1c0Fo7TUEukAABaXCGooSI150.png "style=" float: none; "title=" Daemonret.png "alt=" Wkiol1c0fo7tueukaabaxcgoosi150.png "/>


The program runs to the "signal:0" output, but this is not a dead loop, because the first fork causes the parent process to exit, at which point the shell thinks the current job is complete and will put bash in front of the foreground, but this time the daemon process has lost control terminal while calling Setsid , but still be able to read and write, so still will print out information, just no longer as a control terminal, with the jobs command to view the background and can not see, you can use the following command to view:


650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/80/01/wKiom1c0FbHTc847AAC4GcHZTNQ745.png "style=" float: none; "title=" Daemon.png "alt=" Wkiom1c0fbhtc847aac4gchztnq745.png "/>


View results found that there is a daemon process of their own writing, you can see that its process group ID and session ID are the process that called the SETSID function in the previous run program results and then fork and quit again, and its TTY is not associated, so daemon is a daemon.

-------------------------------------------------------------------------------------------


In the above listed system daemon, there is a crond daemon, the role of this process is to perform regular tasks or wait for some tasks, in the directory/etc can be viewed in the relevant files:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/80/04/wKiom1c0Q2fxD3zRAABqsdndTqE037.png "title=" Crond.png "alt=" Wkiom1c0q2fxd3zraabqsdndtqe037.png "/>


Cron.allow inside the user name, to identify whether to allow users to have their own cron scheduled tasks, the first is not the file, can be added by the super user;

Cron.deny inside is stored a prohibit users to use the cron daemon process;

Open crontab File:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/80/04/wKiom1c0RJ2ComVOAAAZ116tzzs965.png "title=" Crontab.png "alt=" Wkiom1c0rj2comvoaaaz116tzzs965.png "/>

Each user can have their own crontab file, and the format of the file content, such as: each of the location of the * number is a point in time, the latter is scheduled to perform tasks;

* Indicates every minute (hour, week, month ...) ) are to be implemented;

*/n means every n minutes (hours, weeks ...) Implementation

T1--t2 said to be executed in the t1--t2 time period;

T1,t2,t3 said to be executed at t1,t2,t3 time respectively;


Crontab-e can edit user crontab file content, if not specified user is the current user;

Crontab-l display the user's crontab file contents;

Crontab-r Delete User's crontab file;

Crontab-u set a user's Cron service, which is usually super user;


Other than that:

Service Crond start cron services;

Service Crond stop cron services;

Service Crond restart Restart cron service;

Service Crond Status View current cron status


The user's crontab file is stored in the directory/var/spool/cron, the file name is the user name;

For example, write the command in the root crontab file:

*/1 * * * * echo You should drink some water ... >> test.txt


Restart the cron service and use Tail-f to view: 650) this.width=650; "Src=" http://s3.51cto.com/wyfs02/M00/80/02/ Wkiol1c0s62ghkfkaaamw513dyi709.png "title=" Crondret.png "alt=" Wkiol1c0s62ghkfkaaamw513dyi709.png "/>

As shown above, a word is appended to the Test.txt file every other minute, which completes the user's own scheduled task.



Finish

This article is from the "Knock Code good Sleep zzz" blog, please be sure to keep this source http://2627lounuo.blog.51cto.com/10696599/1772746

Linux ———— daemons and Crond timed tasks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.