View Linux Processes

Source: Internet
Author: User
Tags glob

View Linux Processes

Linux Process

Processes are the basic unit of Transaction Management in Linux. All processes have their own independent processing environment and system resources, and they cannot directly access the resources of the other party, inter-process communication requires a specific mechanism (IPC ).

In the Linux kernel header file (/usr/src/kernels/kernel version/include/linux/sched. h) defines the process control block (PCB) struct task_struct to manage the resources of each process.

Process resources are divided into two parts: kernel space process resources, user space process resources

Kernel space process resources: PCB related information, control the block itself, open file table items, current directory, current terminal information, basic thread information, accessible memory space, PID, PPID, UID, and EID.

User process space resources: Memory space mapped by mm_struct is actually the process code segment, data segment, heap, stack, and accessible shared library memory space. These resources are automatically released when the process exits. You can query

View the accessible address space in the/proc/{pid}/maps file.


Process status: Ready, running, waiting (can be interrupted, can not be interrupted), stopped, dead

The Process status is defined in the/usr/src/kernels/kernel version/include/linux/sched. h header file.

/* * Task state bitmask. NOTE! These bits are also * encoded in fs/proc/array.c: get_task_state(). * * We have two separate sets of flags: task->state * is about runnability, while task->exit_state are * about the task exiting. Confusing, but this way * modifying one set can't modify the other one by * mistake. */#define TASK_RUNNING0#define TASK_INTERRUPTIBLE1#define TASK_UNINTERRUPTIBLE2#define __TASK_STOPPED4#define __TASK_TRACED8/* in tsk->exit_state */#define EXIT_ZOMBIE16#define EXIT_DEAD32/* in tsk->state again */#define TASK_DEAD64#define TASK_WAKEKILL128#define TASK_WAKING256#define TASK_PARKED512#define TASK_STATE_MAX1024

The status transition between processes is shown below:


Process attributes

Attributes of processes: PID (process number), PPID (parent process number), PGID (process group number), SID (session ID)

Call the getpid () function to obtain the PID of the current process. The function is declared in the/usr/include/unistd. h header file;

Call the getppid () function to obtain the PID of the parent process of the current process. This function is declared in the/usr/include/unistd. h header file;

Call the getpgid (_ pid_t _ pid) function to obtain the process group number of the specified process _ Pid. This function is declared in the/usr/include/unistd. h header file;

Call the getsid (_ pid_t _ pid) function to obtain the session id sid of the specified process _ Pid (the session is a set of one or more processes ), this function is available in/usr/include/unistd. h declaration in the header file;


Process User attributes: RUID (real User ID), RGID (real user group ID), EUID (valid user ID), EGID (valid user group ID)

Call the getuid () function to obtain the real user RUID of the process (the user who executes the program creates the UID of the process user for the process ), this function is available in/usr/include/unistd. h declaration in the header file;

Call the geteuid () function to obtain a valid user ID, which is declared in the/usr/include/unistd. h header file;

Call getgid () to obtain the user group ID of the process (the Group Number of the user who created the Process). This function is declared in the/usr/include/unistd. h header file;

Call getegid () to obtain the valid process user group ID. This function is declared in the/usr/include/unistd. h header file;


Process Management

Create processes fork and vfork

In Linux, the main method to create a process is to call the fork function. All processes in Linux are directly or indirectly created by the init process (the first process PID = 1). The fork function is declared in the/usr/include/unistd. h header file;

If the fork function is called, two process branches (parent process and child process) are generated. In the parent process, the ID of the child process (greater than 0) is returned, and 0 is returned in the child process; if the call fails, 0 is returned in the parent process;

The following is a program that calls the fork function.

#include<stdio.h>#include<unistd.h>int main(){        pid_t pid;        if( (pid=fork()) == -1 ) //call fork() and test if succeed        {                printf("fork error!");                return -1;        }        else if(pid == 0)  //in sub thread        {                printf("This is sub thread.\n");                printf("in sub : My PID = %d\n",getpid());                printf("in sub : My PPID = %d\n",getppid());        }        else   //in father thread        {                printf("This is father thread.\n");                printf("in father : My PID = %d\n",getpid());        }        return 0;}

Child process and parent process

The sub-process copies all the information of the user space of the parent process (File Buffer, code segment, data segment, BSS segment, heap, stack, and file descriptor). Only the file descriptor is copied, however, the core file table items (struct file structure) associated with the file descriptor are shared.

In the following program, although the child process copies the file descriptor fd of the parent process, it operates on the same file as the parent process.

# Include <sys/types. h> # include <stdio. h> # include <unistd. h> # include <fcntl. h> # include <string. h> # include <stdlib. h> int main (int argc, char * argv []) {pid_t pid; int fd; int I = 1; int status; char * delimiter = "hello "; char * ch2 = "world"; char * ch3 = "IN"; if (fd = open ("test.txt", O_RDWR | O_CREAT, 0644) =-1) // open a file {perror ("parent open"); exit (EXIT_FAILURE);} if (write (fd, failed, strlen (failed) =-1) // The parent process writes the string 1 {perror ("parent write"); exit (EXIT_FAILURE);} if (pid = fork () =-1) to the file) // create a sub-process {perror ("fork"); exit (EXIT_FAILURE);} else if (pid = 0) // {I = 2 in the sub-process; printf ("in child \ n"); printf ("I = % d \ n", I); if (write (fd, ch2, strlen (ch2 )) =-1) // The child process copies the fd of the parent process, and then writes the string 2 perror ("child write"); return 0;} to the file ;} else {sleep (1); // sleep for 1 second, waiting for the sub-process to finish executing printf ("in parent \ n"); printf ("I = % d \ n ", i); if (write (fd, ch3, strlen (ch3) =-1) // The parent process writes the string 3 perror ("parent, write "); wait (& status); // wait until the sub-process ends and return 0 ;}}

Use vfork to create a process

Using fork to create a process copies a large amount of data in the user space of the parent process. In some scenarios, this is a great waste. Therefore, when using vfork to create a new process, it does not copy the address space of the parent process, instead, you can apply for a new storage space only when necessary. vfork can greatly improve the performance than fork. Vfork only copies as needed. Generally, it shares all resources with the parent process.

The following program describes the shared data segments and code segments of sub-processes and parent processes created by vfork.

#include<unistd.h>#include<error.h>#include<sys/types.h>#include<stdio.h>#include<stdlib.h>int glob=6;int main(){        int var;        pid_t pid;        var=88;        printf("in beginning:\tglob=%d\tvar=%d\n",glob,var);        if((pid=vfork())<0)        {                perror("vfork");                exit(EXIT_FAILURE);        }        else if(pid==0)        {                printf("in child,modify the var:glob++,var++\n");                glob++;                var++;                printf("in child:\tglob=%d\tvar=%d\n",glob,var);                _exit(0);        }        else        {                printf("in parent:\tglob=%d\tvar=%d\n",glob,var);                return 0;        }}

The above program shares the glob and var variables. If you change vfork in the above process to fork, the results will be different.


End Process

Stopping a process means that the resources of the process need to be recycled. It can also be divided into resources of the process user space and resources of the Process kernel space.

Reclaim user process space resources

Before a process Exits normally, it needs to execute operations such as exit processing function, refresh the stream buffer, and then release all the resources of the user's process space. The resources PCB of the process in the kernel will not be released immediately, the process that only calls the exit function and does not recycle the kernel resources PCB is a zombie process.

The displayed call exit or _ exit system call can end the process. Call exit to execute the cleaning function registered by the on_exit and atexit functions in reverse order, refresh the buffer, and return the exit status to the parent process. _ Exti exits directly. It only submits the exit status to the parent process and does not clean up or refresh the buffer.

Note: The difference between exit and return is that exit the current process, while return only exits the current function.

Reclaim kernel space resources

The resources to recycle the kernel space are not completed by the exit process, but by the parent process of the process. The parent process that calls the wait function will block the process and wait for any sub-process of the process to end and reclaim the resources in the kernel space of the sub-process, the wait function is defined in/usr/include/sys/wait. h header file. You can also use the waitpid function to Wait for the end of the specified sub-process, which is defined in/usr/include/sys/Wait. h.


Orphan and zombie Processes

Orphan process: because the parent process exits, a child process adopted by the init process is called an orphan process, that is, the parent process of the orphan process is changed to the init process.

Zombie process: the process has exited (the user space resources have been recycled), but the process whose father process has not recycled the kernel resources is called a zombie process, that is, the PCB of the process in the kernel space is not released.

The following program demonstrates an orphan Process

#include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(){        pid_t pid;        if((pid=fork())==-1)                perror("fork");        else if(pid==0)        {                printf("sub : pid=%d,ppid=%d\n",getpid(),getppid());                sleep(2);                printf("sub : pid=%d,ppid=%d\n",getpid(),getppid());        }        else        {                printf("father : pid=%d,ppid=%d\n",getpid(),getppid());                sleep(1);                exit(0);        }}

The following program demonstrates a zombie process.

#include<stdio.h>#include<unistd.h>#include<stdlib.h>int main(){        pid_t pid;        if((pid=fork())==-1)                perror("fork");        else if(pid==0)        {                printf("child_pid pid=%d\n",getpid());                exit(0);        }        sleep(3);        system("ps");        exit(0);}

Program running result:


The PID = 10375 process in the running result is frozen. If/proc/10375/maps is enabled (the user process space information of the process), it can be found to be empty, that is, the user's process space resources have been recycled.


Daemon

A daemon is a special process running in the background. It is out of the terminal, so that the daemon can be prevented from being interrupted by any terminal signal, and the information generated by its execution is not displayed on any terminal. When a daemon periodically executes a task or waits for some events to be processed, most Linux servers use daemon, such as httpd.

Generally, daemon can be started in the following ways:

(1) Start the script at system startup, usually in the/etc/rc. d directory;

(2) Use the inet super server to start, such as telnet;

(3) The process started regularly by the cron command and started with the nohup command on the terminal is also a daemon process.


To create a daemon, follow these steps:

(1) shielding a signal related to control terminal operations

(2) run in the background. The method is to create a child process in the process and terminate the parent process so that it runs in the background of the child process.

(3) Remove the terminal control and process group because a process belongs to a process group and shares a control terminal with the process group, the control terminal and process group associated with a process are generally inherited from the parent process, so the child process is still affected by the parent process terminal. You can use setsid () to make a sub-process become a new session leader and process leader. The sub-process is not associated with the original process group.

(4) prohibit the process from re-opening the control terminal. The process has become an end-less session leader, but still has the permission to apply for a terminal. Only the session leader can open the terminal. The method is to create a child process and exit the parent process. The child process is no longer a session leader, and the parent process has no terminal control.

(5) disable the opened file descriptor. The sub-process will copy the file descriptor from the parent process, which is meaningless to the daemon process. Instead, it will waste system resources and cause the file system occupied by the process to be unmounted.

(6) change the current working directory. When a process is active, the file system of the working directory of the process cannot be detached. Therefore, the working directory of the daemon process is usually set as the appropriate directory.

(7) reset the mask created by the file. A process inherits the file creation mask umask from the parent process. It may modify the storage permissions of the files created by the daemon. Generally, the file creation mask is cleared.

(8) process the SIGCHLD signal (sub-process exit signal ).





How to view all processes on linux

Ps-aux view all processes
Top and uptime can be used to view the running status of your system.
If you want to view the specific process or service listening port
You can use netstat-an | grep 'Your service, or port '.

Kill processes in LINUX

Kill-9 process no.

Ps-ef | more to check the process

If you know the process name, you can also use

Ps-ef | grep process name

Locate the process number in the second column and enter the kill-9 process number.

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.