View, create, session, daemon, end of process

Source: Internet
Author: User
Tags exception handling session id

Environment variable Operation function

Char*getenv (const char* name); Get environment variable value

Intputenv (cahr* str); A string of name=value, put it in the environment table, and delete its original definition if name already exists

Intsetenv (Name,value,rewrite);

INTUNSETENV (name); Delete the definition of name

setjmp function: Set the jump point of nonlocal jump

longjmp function: Non-local jump

C program lacks the syntax of exception handling, you can use nonlocal jump to handle C program exceptions

ATo view process information by command:
PS ID View process ID number ps–u view process status Ps–x
Ps–aux View All Processes
The USER process is the main PID process ID PPID The parent process%cpu the CPU percent of the process%mem the nice value of the NI process, which indicates that it takes less CPU time VSZ process virtual size Number of pages in RSS hosting TTY terminal ID Wchan waiting process resource start time of process consuming CPU Time command command name and parameters ST At process status: (Run State stat=r wait state stat=s stop state stat=t Zombie State stat=z)
CTRL+Z suspend process FG Resume paused process

Two. Get the process and process group IDs function settings process and process group IDs

Pid_tgetpid (void) Gets the current process ID

Pid_tgetppid (void) Gets the parent process ID of the current process

Pid_tgetuid (void) Gets the actual user ID of the current process

Uid_tgeteuid (void) to obtain a valid user ID for the current process

Pid_tgetgid (void) Gets the user group ID of the current process

Pid_tgetpgid (void) Gets the process group ID of the process

Pid_tgetpgrp (void) obtains the process group ID getpgid (0) =getpgrp ()

Pstree Command View process tree

int Setpgid (pid_t pid, pid_t pgid); Set the process ID of the current process to the group ID that the current process belongs to

Function: Sets the parameter PID specifies the group ID to which the process belongs to the parameter pgid the specified group ID. If the parameter PID is 0, it is used to set the group ID for the current process, and if the parameter pgid is 0, the process ID specified by the PID will be used as the process group ID. A process can set the process group ID only for itself or its child processes.

Return value: The group identifier was returned successfully, error returned-1, and the reason for the error is in errno.

Error code

The einval parameter pgid is less than 0.

The eperm process does not have sufficient permissions to complete the call.

Esrch cannot find a process that is specified with the parameter PID


PID is used to specify the process ID to modify. If 0, the current process.

Pgid is used to specify the new process group ID. If 0, the current process.

Setpgid (0,0) is equivalent to SETPGRP (0,0)//make the current process the leader of the new process group



Example 1: function to get process and process group IDs

5 int Main ()

6 pid_t PID; 7
8 if ((Pid=fork ()) <0)

9 printf ("fork error!");

else if (pid==0)

printf ("The child process PID is%d.\n", getpid ());
printf ("The Group ID is%d.\n", getpgrp ());
printf ("The Group ID is%d.\n", Getpgid (0));
printf ("The Group ID is%d.\n", Getpgid (Getpid ()));
Exit (0);

Sleep (3);
printf ("The parent process PID is%d.\n", getpid ());
printf ("The Group ID is%d.\n", getpgrp ());
return 0;

Process Group ID = parent Process ID, that is, the parent process is the leader process

Example 2. Set process and process group IDs

Leader Process identity: its process group id== its process ID

The leader process can create a process group, create processes in the process group, and then terminate

The process group exists as long as there is a process in the process group, regardless of whether the leader process is terminated

Process Group lifetime: Process group creation to last process departure (terminate or move to another process group)

A process can set the process group ID for itself or a child process

Setpgid () Join an existing process group or create a new process group

Eg: parent process changes the group ID of itself and child processes

5int Main () {
6 pid_t PID;
8 if ((Pid=fork ()) <0) {
9 printf ("forkerror!");
Ten exit (1);
One}else if (pid==0) {
printf ("The child process PID is%d.\n", getpid ());
printf ("The group ID of child is%d.\n", Getpgid (0));//return group ID
Sleep (5);
printf ("The Group ID of child being changed to%d.\n", Getpgid (0));
Exit (0);
Sleep (1);
Setpgid (PID,PID); The group ID that changes the subprocess is the child process itself 21
Sleep (5);
printf ("The parent process PID is%d.\n", getpid ());
printf ("The parent of parent process PID is%d.\n", getppid ());
printf ("The Group ID of parent is%d.\n", Getpgid (0));
Setpgid (Getpid (), Getppid ());//Change the parent process's group ID to be the parent process of the parent process
printf ("The Group idof parent is changed to%d.\n", Getpgid (0));
return 0;

Three. Create a process

Pidfork (void) creation process

Pidvfork (coid) creates a process that does not copy the address space of the parent process completely into the child process and does not copy the page table.

The subprocess runs directly in the stack space of the parent process after the vfork () returns, and uses the memory and data of the parent process. This means that a child process can destroy the parent process's data structure or stack, causing a failure.

Vfork guarantees that the subprocess runs first, and that the parent process may not be scheduled to run after she invokes exec or exit. If the child process relies on further actions of the parent process before the two functions are called, the deadlock is caused

#definetypedef _std_tpye

Four. Status of the process

1. Can run

2. Waiting for

3. Suspension

4. Zombies view process status through top command

Orphan process: Parent process End child process not finished, subprocess ended by 1th process

Zombie Process: End of subprocess but not fully free memory (task_struct in memory not released). The zombie process will be adopted by the INIT process after the parent process is finished and eventually reclaimed

Avoid zombie processes: The process sends a SIGCLD signal to the parent process before it terminates, the parent process calls wait (Int*status) or Waitpid (Pid_tpid, Int*status,int opration), and waits for the child process to exit. If the child process does not call exit, the parent process wait enters the block.

Five. Priority of the process nice setpriority getpriority

The lower the priority value, the higher the priority.

Priority is determined jointly by the humility value (NI) of the priority level (PR) + process.

The PR value is inherited by the parent process and is not modifiable.

Linux provides nice system calls to modify the NI value of itself; SetPriority system calls can modify the NI values of other processes and process groups.

#include <unistd.h>
#include <errno.h>
#include <sys/resource.h>
#include <stdlib.h>
#include <stdio.h>
Main ()
int nPr;
if (Nice (3) = = 1) The humility value of the process is 3, the priority is reduced
Perror ("nice");
Exit (0);
errno = 0;
NPr = GetPriority (Prio_process,getpid ());//Get the humility value of the current process
if (errno!= 0)
Perror ("getpriority");
Exit (0);
printf ("Priority is%d\n", nPr);


Priority is 3

Six. End old process open new process

1. Exec family functions: A total of 6,

#include <unistd.h>

extern char **environ;

int execl (const char *path, const char *arg, ...);

int EXECLP (const char *file, const char *arg, ...);

int execle (const char *path, const char *arg, ..., Char *const envp[]);

int execv (const char *path, char *const argv[]);

int EXECVP (const char *file, char *const argv[]);

int Execve (const char *path, char *const argv[], char *const envp[]);

Only Execve is a real system call, others are packaged library functions on this basis.

Function: Executes an executable file inside the calling process. The executable file here can be either a binary file or a script file that can be executed under any Linux.

After other programs are executed through the EXEC function, the newly opened process overwrites the current program process (King), does not return a value, and only the call fails, they return a-1, which is executed from the call point of the original program.

2.system (constchar* comment); System =fork+exec+waitpid

Example 1---------------------------------
System ("Your_program");
printf ("You can me!"); After your program has finished executing, the printf statement is executed
Example 2---------------------------------
EXEC ("Your_program");
printf ("You can ' t-me!"); Because exec replaces the program Your_program itself, the program no longer executes the printf statement
Under Linux, exec is usually used with fork statements. Look at this example below.
pid_t pid = fork ();
if (PID < 0) {
printf ("fork error!");
Exit (-1);
else if (PID = = 0) {//This is a child process
printf ("I ' m son!");
printf ("Subprocess id=%d, her parent process id=%d\n", getpid (), Getppid ());
EXEC ("Your_program");/execute other programs
else {//This is the parent process
printf ("I ' M father!");
printf ("Subprocess id=%d, her parent process id=%d\n", getpid (), Getppid ());
EXITLP ("\bin\ls", "mingling", NULL); If this is the case, it will not be executed.
Wait ()//To return after child process is finished
Exit (0);

The difference between exec and system

(1) Exec is directly with the new process to replace the original program to run, after the operation is not back to the original program.

(2) system is to invoke the shell to execute your command, system=fork+exec+waitpid, after execution, go back to the original program. Continue to the following section.

In short, if you call with Exec, you should first fork a new process and then exec. and system does not need you to fork the new process, has been encapsulated well.

Seven. Session:

1. Concept: A collection of one or more process groups, starting with the user login, terminating the user exit. All processes in this period belong to this session period

2. pid_t setsid (void) function

Function: After calling Setsid () in a subprocess, the subprocess becomes the new session header process and becomes a leader process with a process group ID equal to the session ID

Usage: The calling process is not a leader process, then a new session is created.

• This process becomes the new session header process (Sessionheader)

• The process becomes the leader of a new process group.

• The process has no control terminal and will be interrupted if it is previously available

The group leader process cannot become the new session first process, the new session first process will certainly become the leader process ...

Get session pid_t GetSID (pid_t pid) function

Return value: Successfully returns the process group ID of the session's first process, error return-1

5 int main () {
6 pid_t PID;
8 if ((Pid=fork ()) <0) {
9 printf ("forkerror!");
Ten exit (1);
One}else if (pid==0) {
printf ("The child process PID is%d.\n", getpid ());
printf ("The Group ID is%d.\n", Getpgid (0));
printf ("The session ID of ' child is%d.\n", GetSID (0));
Sleep (10);
Setsid (); The subprocess is not a leader process, so it becomes the new session first process, and becomes the leader process. The Process group ID is the session process
printf ("changed:\n");
printf ("The child process PID is%d.\n", getpid ());
printf ("The Group ID is%d.\n", Getpgid (0));
printf ("The session ID of ' child is%d.\n", GetSID (0));
Sleep (20);
Exit (0);
0 return;

Eight. Daemon process

1. The concept of Linux most services are implemented through the daemon, complete many system tasks

0: Dispatch process, called Exchange process (swapper), kernel part, system process

1:init process, kernel call, responsible for booting Linux system after kernel boot

Let a process not be affected by user, terminal, or other changes, you must turn this process into a daemon

2. Daemon Process Programming steps

1. Create child process, parent process exits

• All work is done in the child process

• Form out of control terminals

2. Create a new session in a child process

Setsid () function

• Make the child process completely independent and out of control

3. Change the current directory to the root directory

chdir () function

• Prevent the use of an unloaded file system

• can also be replaced by other paths

4. reset File Permission Mask

umask () function

• Prevent inherited file creation masked words from denying certain permissions

• Increased daemon Flexibility

5. Close the file descriptor

• Inherited open files are not used, wasting system resources, unable to uninstall

getdtablesize ()

• Returns the number of items in the file descriptor Chart of the process in which the process opened

9 int main () {
Ten pid_t pid;
one int i,fd;
The char *buf= "This is a daemon program.\n";
if ((Pid=fork ()) <0) {
printf ("forkerror!");
Exit (1);
}else if (pid>0)//fork and exits the parent process
Exit (0);
Setsid (); Create a new session in a child process.
ChDir ("/"); Set working directory as root
Umask (0); Set a permission mask
For (I=0;i<getdtablesize (); i++)//getdtablesize returns the number of items in the child process file descriptor
Close (i); To close these file descriptors that are not used
while (1) {//Dead loop token it will always run
27//Read-write mode to open "/tmp/daemon.log", the returned file description assignments to FD
if (Fd=open ("/tmp/daemon.log", o_creat| o_wronly| o_append,0600) <0) {
printf ("Open file error!\n");
Exit (1);
Write (Fd,buf,strlen (BUF) +1); To write buf into FD.
Close (FD);
Sleep (10);
printf ("neveroutput!\n");

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: 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.