Linux system programming

Source: Internet
Author: User

Course Objectives:

Build a multi-client instant Messaging/chat room project based on a host system

Theoretical knowledge involved in Process Control: Zombie process/orphan process, Process control, daemon ... interprocess communication: Pipelines, Named pipes, signals ... Multi-threaded programming: locks, semaphores ...

Reference Tutorials

Robert Love, Linux System program

Process structure

Process consists of three parts, program, data and Process Control

Process status

Task_running (Run): R executable state. Executing, waiting in the ready queue.

Task_interruptible (interruptible): S sleep (blocked). If the condition is met, the kernel sets its state to run. Received a signal and were awakened early and put into operation.

task_uninterruptible (non-interruptible): D is in the same interruptible state but not awakened by receiving a signalTask_zombie (Zombie): Z The process has ended, but its parent process has not yet called wait (), and the process descriptor for the child process is still preserved. task_stopped (stop): T stops execution. This state occurs when a signal such as Sigstop, SIGTSTP, Sigttin, Sigttou is received. In addition, any signal received during debugging will cause the process to enter this state. view of process statusPS: Shows the status of the instantaneous processCommon parameters:

L: Long format output

U: Show process by user name and start time order

J: Display processes in task format

F: Display the process in a tree-shaped format

A: Show all processes for all users

X: Show the process without control terminal

R: Show Running Processes

WW: Avoid verbose parameters being truncated

$ps//List the current user's processes in the current shell

$ps –u Yuhong//List all processes run by user Yuhong

$ps –el//Show all processes running in a detailed list

$ps aux//Show All processes running in detailed BSD style

%MEM: Utilization of memory consumed

VSZ: Virtual memory size, that is, a program that completely resides in memory, requires more Less memory space

RSS: How much memory is currently in use

STAT: Process Current state (R/S/D/Z/T)

Suffix:

         < (high-priority process)N (Low-priority process)L (Memory lock page)s (This process is the session first process)+ (foreground process)L (multithreaded process)

Process creation and termination

1, the creation of the process

Create function: pid_t fork (void); (The parent process returns, fork () returns the child process ID, returns in the child process, and fork () returns 0. When the number of processes reaches the upper limit or insufficient memory, there may be an error, the return value is-1, the system call does not directly return the error code, but the error is stacked in the global variable errno)

The value of errno in various error cases: 1) The process reaches the upper limit Errno=eagain

2) Insufficient system memory Errno=enomem

See the meaning of errno values errno.h man 3 errno

Get process id:getpid (); Getppid ();

The orphan process should be avoided (the orphan process is not over, the parent process is over), and the workaround is to tuogu the child process or let its parent process finally exit.

Child process Tuogu: Init process (pid=1) takes over.

  

  Questions:

How do I implement a subprocess Tuogu? Why is the child process in fork () Example 3 able to tuogu to the Init process after the parent process exits (does the parent process exit automatically tuogu without extra action)?

Fork () Example 3 why is there a parent process in the original process?

What are the child processes that inherit from the parent process? Example of a trial code.

  

2.two special processes in Linux

Process # No. 0: Ancestors of all processes

Swapper process (scheduling process): Responsible for inter-process scheduling, kernel direct control, user process can not access.

Execute the Cpu_idle () function

No other process is in task_running, the kernel chooses the No. 0 process to run

Process # 1th created by process No. 0

The initialization process is called at the end of the kernel boot process and is used to initialize the system environment. The initialization file is a file in the/erc/rc* file, the/etc/inittab file, and the/ETC/INIT.D directory. The initialization process never exits.

Init process creates and monitors activities of other processes

Take over the orphan process

3 . Termination of the process

1) Explicit system calls

#include <stdlib.h>void exit (int status);    Write back the contents of the file buffer before exiting the file # include <unistd.h>void _exit (int status);    Buffer data loss after exiting

After these two functions are called, the process is converted to a zombie process.

    

2) leave from the end of the program

3) terminated by signal SIGTERM (signal terminate) SIGKILL

Kill [-S < signal name or number >][program]

Kill [-l < signal number;]
If you do not add the < info number > option, the-l parameter lists all the information names.

Forcibly abort (kill) a process with PID 324:
#kill-9 324

#free

  Questions:

What are the signals in process management, and what are the numbers, and how are they used?

4) killed by the kernel segmentation violation

The kernel kills the process when an exception occurs.

The process termination kernel transmits a SIGCHLD (signal child) signal to its parent process

If a child process disappears when it terminates, the parent process will not be able to retrieve any information

If the child process ends before its parent process, the kernel should let the child process into the state of the zombie process, waiting for the parent process to inquire about its state, and after the status inquiry, the zombie process will officially end.

Kernel data structures for zombie processes

The zombie process retains only the smallest skeleton: PID of the process, exit status, run time

Avoidance of Zombie Processes:

I parent processes wait for the child process to end through functions such as wait and waitpid (causing the parent process to block itself immediately until a child process exits).

     #include <sys/types.h>

#include <sys/wait.h>

pid_t Wait (int *status); Wait (&status) =>waitpid ( -1,&status,0)

return value: 1. End of child process PID 2.-1, if no child processes

     status (two bytes): 1. High-byte: The code that is set when the child process exits, and the low byte is 0 2. If the child process is exited because the signal is received, the low byte is the encoding of the signal

Sometimes you see that the parameter of the wait function is NULL, indicating that the parent process does not care about the state of the child process, just waits for the child process to end and obtains the child process information to prevent it from becoming an orphan or zombie process.

pid_t waitpid (pid_t pid, int *status, int options);

PID Value:

①<-1: End of child process waiting for the process group ID to be PID②-1: Waits for the end of any child process (any one)③ 0: Wait for the process group ID to end with the same child process as the parent process group ID④>0: End of child process waiting for process ID PID     

Options can be one or more of the following constants

①wnohang: Returns immediately if no child process exits②wuntraced: Returns if a child process is stopped③wcontinued: Return (send Sigcont) If a stopped child process starts executing againII If the parent process is busy, you can use the signal function to install handler for SIGCHLD, because when the child process finishes, the parent process receives the signal and the wait recycle can be called in handler.signal system calls:function Description: Installs a new processing handle for the specified signal. The signal processing handle may be a user-specified function, sig_ign or SIG_DFL. When the signal arrives, if its handle is SIG_DFL, the signal is processed by default, and if its handle is sig_ign, the signal is ignored, and finally, if the handle is a user-specified function, the signal processing method is reset to SIG_DFL at this point. It is then possible to block the signal in processing and, finally, to call the signal processing handle.

Usage:

#include <signal.h>typedef void (*sighandler_t) (int); sighandler_t signal (int signum, sighandler_t handler);

Parameters:
Signum: Signal encoding.
Handler: A new signal processing handle.

Return Description:
When executed successfully, returns the previous signal processing handle. Failed to return Sig_err.

III If the parent process does not care what time the process ends, the kernel can be notified with signal (sigchld,sig_ign), the kernel is recycled, and no longer sends a signal to the parent process. ivStevens Two fork to avoid the zombie process: is the fork two times, the parent process fork a child process, and then continue to work, the child process fork a grandchild process after exiting, then the Sun process is init takeover, after the sun process is finished, Init will be recycled. But the recycling of the sub-process to do it yourself.

Status flag:

  

Signal:

  

    

Three ways to perform multitasking: polling, interrupts, DMA (the difference from interrupts)

  Questions:

Why two fork can tuogu the grandchild process to the init process?

  

What is the handler handle?

The signal processing handle may be a user-specified function, sig_ign or SIG_DFL.

4. Process Group

A collection of one or more processes

Job Control

Getpgrp () & Setpgid ()

  

To be Continued ...

Linux system programming

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.