Linux Process Control (iii)

Source: Internet
Author: User
Tags syslog

1. Inheritance of open files between Processes 1.1. To inherit open files with fork

The child process after the fork automatically inherits the open file of the parent process, and after inheritance, the parent process closes the open file without affecting the child process.

Example:

#include <stdio.h>

#include <fcntl.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/stat.h>

int main ()

{

Char szbuf[32] = {'} '};

int iFile = open ("./a.txt", o_rdonly);

if (fork () > 0) {//parent process

Close (IFile);

return 0;

}

Child process

Sleep (3); Wait for parent process closing FD

if (read (IFile, szbuf, sizeof (SZBUF)-1) < 1) {

Perror ("read fail");

}else{

printf ("string:%s\n", szbuf);

}

Close (IFile);

return 0;

}

1.2. Daemon Process

Daemon running in the background is also known as a "background service process." It is not the process of controlling the terminal with which it is connected. It is independent of the execution of certain tasks with control terminals, usually cycles. So why is the daemon running out of the terminal background? The daemon is detached from the terminal in order to prevent the information in the process of execution from appearing on any terminal and the process will not be interrupted by any terminal information generated by any terminal. So why introduce a daemon? Because in Linux, each system communicates with the user interface called the terminal, each process which starts from this terminal will depend on this terminal, this terminal is called these Process Control terminal. When the control terminal is closed, the corresponding process will be automatically closed. But the daemon can break through this limitation, and it will be executed until the entire system shuts down. Almost all server programs, such as Apache and WU-FTP, are implemented in the form of daemon processes. Many of the commands common to Linux, such as inetd and ftpd, are usually referred to as daemon at the end of the letter d.

Features of the daemon:

The most important feature of the 1> daemon is running in the background.

2> second, the daemon must be isolated from the environment before it runs. These environments include file descriptors that are not closed, control terminals, sessions and process groups, working directories that have file creation masks, and so on. These environments are usually inherited from the parent process by the daemon.

How the 3> daemon starts

Programming rules for the daemon process

L Create child process, parent process exits:

Calling fork produces a child process while the parent process exits. All of our follow-up work is done in the child process. In doing so we can hand over control of the console and prepare the subprocess as the process leader; Because the parent process exits before the child process, it causes the child process to have no parent process and becomes an orphan process (orphan). Whenever the system discovers an orphan process, it is automatically adopted by the 1th process, so that the original child process becomes a subprocess of process 1th. The code is as follows:

PID = fork ();

if (pid>0)

Exit (0);

L Create a new session in a child process:

Use the system function Setsid (). Because the first step in creating the daemon calls the fork function to create the child process, and then exits the parent process. Because when the fork function is called, the child process copies the parent process's session, process group, control terminal, etc., although the parent process exits, but the session, process group, control terminal has not changed, so it is not really independent. While calling the SETSID function will create a new session and from the leader of the session, call the SETSID function has the following 3 functions: Let the process out of control of the original session, let the process out of the original Process group control, let the process from the original control terminal control;

Process group: is a collection of one or more processes. The process group has a process group ID to uniquely identify. In addition to the process number (PID), the Process group ID (GID) is also an essential attribute of a process. Each process has a leader process, and the process number of its leader process equals the process group ID. And the process group ID is not affected by the exit of the leader process.

Session Period: The session period is a collection of one or more process groups. Typically, a session starts at the user logon and terminates when the user exits, during which all the processes that the user runs are part of the session period.

Control Terminal: Because in Linux, each system communicates with the user interface called the terminal, every process which starts from this terminal will depend on this control terminal.

L Change the current directory to the root directory:

A child process created with the Fork function inherits the current working directory of the parent process. Because in the process of running, the current directory is located in the file can not be uninstalled, which will cause a lot of inconvenience to later use. Use ChDir ("/") to switch the current working directory to the root directory.

L Reset File Permission mask:

Umask (0); Setting the file permission mask to 0,deamon creates files is not too much trouble;

L Close all unwanted file descriptors:

The new process inherits some files that have already been opened from the parent process. These files that are opened may never be read and written by the daemon, and they consume system resources all the time. In addition, the daemon has lost contact with the terminal, then the characters entered from the terminal cannot reach the daemon, and the characters output by regular methods (such as printf) in the daemon cannot be displayed on the terminal. Therefore, all file descriptors from 0 to Maxfile are usually closed.

for (i=0;i<maxfile;i++)

Close (i);

(Note: Sometimes the SIGCHLD signal signal (SIGCHLD, sig_ign) is processed, and the zombie process is prevented (zombie))

Below you can add anything you want to daemon do.

Example:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <sys/stat.h>

void Daemon ()

{

const int maxfd=64;

int i=0;

if (fork ()!=0)//parent process exits

Exit (0);

Setsid (); To become the new process group leader and Xinhui session leader, out of control terminal

ChDir ("/"); Set the working directory as the root directory

Umask (0); Resetting the file access permission mask

for (; i<maxfd;i++)//Close All files inherited from the parent process as much as possible

Close (i);

}

int main ()

{

Daemon (); Become Guardian Process

while (1) {

Sleep (1);

}

return 0;

}

Example:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <syslog.h>

#include <sys/stat.h>

#include <time.h>

Main ()

{

int i = 0;

if (fork () > 0)

Exit (0);

Setsid ();

ChDir ("/");

Umask (0);

for (; i <; i++)

{

Close (i);

}

i = 0;

while (I < 10)

{

printf ("%d\n", I);

time_t ttime;

Time (&ttime);

struct TM *ptm = gmtime (&ttime);

Syslog (Log_info, "%d%04d:%02d:%02d", I, (1900 + ptm->tm_year), (1 + ptm->tm_mon), (Ptm->tm_mday));

i++;

Sleep (2);

}

}

By looking at Vi/var/log/messages

Linux Process Control (iii)

Related Article

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.