UNIX Environment C language-process management, interprocess communication

Source: Internet
Author: User
Tags close close message queue new set semaphore signal handler

Process management ******
First, the basic concept
1. Processes and Procedures
A process is a running program, a running program may contain multiple processes, and the process is responsible for performing specific tasks in the operating system
A program is a file stored on a hard disk, it contains machine instructions and data, is a static entity
Process or task it is a computer program that processes active state
2, the classification of the process
A, interactive process: The user can enter data, but also can see the feedback information of the program
b, Batch process: Executable script file (Makefile) composed of the system command each Process Control statement
C, Daemon: a process that has been active, typically run in the background, loaded by the operating system's open script or Super User (init)
3. View Process PS
PS: Simple display of the current user control terminal process
A: Show processes for all users
-U: with detailed information
-X: Includes process without control terminal
-W: Displays at larger widths
4. Information table of the process
User, process number, CPU occupancy, memory occupancy, virtual memory occupancy, physical memory usage, status, start time, run time
5. Status of the process
O Ready State
R Run State
S can be awakened by sleep
D sleep states that cannot be awakened
T paused, received a sigstop signal
X dead State
Z Zombie State
< high-priority
N Low-priority
L Multithreading Process
6. If process A is on process B, process A is the parent process of process B, process B is a child of process a, process a may also have a parent process, and process B may have child processes
7, the child process at the end of the parent process will send a SIGCHLD signal, the parent process after receiving this signal is ignored by default, if the parent process is not collected in a timely manner (show call to wait), the child process is in the zombie state
8, before the parent process dies, it will entrust its child process to the daemon (init), and then send the SIGCHLD signal to his parent process.
9, the operating system assigns each process an identifier, can be obtained using GETPID, when the process is finished, the identifier belongs to it is deferred reuse

Second, Getxxid
Getpid Process Identifiers
Getppid Parent Process Identifier
Actual user User ID of the GETUID process
Actual user group ID of the GETGID process
Valid user ID for the GETEUID process
Valid user group ID for the GETEGID process

Set the group ID identifier and user ID identifier for the process
chmod u+s executable file
chmod g+s executable file
In this way, the executable owner gets a higher privilege than itself.

Third, fork
pid_t fork (void)
Function: Create a child process
Return value: Call two return values at a time
The branch of the parent process returns the process number of the child process, and the parent process can only get the child process ID when the child process is created
Child process returns 0, child process can get ID of parent process at any time
1. A child process created by fork can only resolve a parent-child process by the return value and then the corresponding branch of the process, processing the corresponding task
2. Child processes created by fork Copy the parent process's global segment, static data segment, heap, stack, io stream buffer, and parent-child process shared code snippet, shared file descriptor, file pointer
3, fork return after the call succeeds, the parent-child process who first returns does not necessarily, can through the sleep/usleep to ensure that the parent-child process who first executes
4. When the total number of processes in the system exceeds the system limit, the fork will fail to call
5, Exercise: Use fork with sleep to achieve the zombie process and the orphan process//zfork.c LFORK.C
6, the code before the fork is only the parent process, the code after the fork, the parent process is likely to execute

Iv. vfork
pid_t vfork (void);
Functions: Used to create child processes
The return value is consistent with fork
1. When you create a child process using vfork, the parent process pauses first, and then the parent process starts executing after the child process is completely created
2. Use Vfork to work with the EXEC function to create a child process
if (0 = = vfork ())
{
EXEC Load Child process
}
Parent process
3. Using vfork does not copy any data from the parent process, but instead loads another executable file with the EXEC function, which is more efficient than fork.
4, the EXEC function does not return, the child process must be executed before the parent process

int execl (const char *path, const char *arg, ...);
Path: Executable file path
ARG: A parameter to an executable, similar to a command-line argument, must be null-terminated, the first must be a file name that can be executed
EXECL ("Path", "A.out", NULL);

1, the child process created by Exec will replace the parent process to the code snippet, do not copy the parent process stack, heap, global, static data segments, will replace them with the new executable file
2. Exec simply loads an executable file and creates a process that does not generate a new process number
3. Only the EXEC function execution ends (whether successful or unsuccessful), the parent process can continue execution

int EXECLP (const char *file, const char *arg, ...);
FILE: The filename of the executable file, from the location specified by the PATH environment variable to find the executable file
The parameters are consistent with exec

int execle (const char *path, const char *ARG,..., char * const envp[]);
Path and Arg are consistent with EXECL, but the last to provide an environment variable table

int execv (const char *path, char *const argv[]);
Path is consistent with EXECL, and parameters are provided as pointer data

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

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

V. Normal exit of the process
1, return stats from main, the parent process will get stats low eight bits
2, call the exit (stats) function, the parent process will get stats low eight bits, this function does not return a value
Before the process exits:
A, call atexit, OnExit registered function
B. Flush and close the open file
C. Call the _exit/_exit function again
Stats:exit_success/exit_failure
3, _exit (stats)/_exit (stats) function
The parent process gets stats's low eight bits of data, tuogu before the process exits, sends a SIGCHLD signal to the parent process, and the function does not return
4, the last thread of the process ends

Vi. abnormal exit of the process
1, the process calls the Abort function, triggering the abort signal
2, the process received some signals (exit, segment error, except 0)
3. The last thread received a cancellation request and responded to the cancellation request

Vii. Recycling of Processes Wait/waitpid
#include <sys/types.h>
#include <sys/wait.h>
pid_t Wait (int *status);
Function: Recycles the child process, as long as it is a child process and it is recycled
Status: Returns the end state of the process, as well as the low eight-bit data
To use a macro passed by the system to resolve
When NULL indicates the end state of the child process is not
This call can only reclaim one child process at a time, and any child process that ends it will stop and reclaim the child process, and if you want to use it to reclaim all the child processes must be constantly called until the function returns-1 (stating that there are no child processes)
If a child process is in zombie state before the call, the zombie child process is returned and recycled immediately

pid_t waitpid (pid_t pid, int *status, int options);
Function: To reclaim the specified child process
PID: The ID of the child process to be recycled
<-1 waiting for process group ID is the absolute value of the PID process
-1 wait for any process to end
0 waiting for a child process that is in the same group as the parent process to end
>0 waiting for the specified child process to end
Options: If the specified process does not end, block

Signal processing ******
First, the basic concept
1. Interrupt: Abort (not terminate) the task being performed by the current program, in turn to perform other tasks
Hard interrupts: interrupts triggered by a hardware device (key of the phone)
Soft interrupts: Interrupts triggered by other programs (signals, signals and slots in QT)

2. Unreliable signal
A, less than sigrtmin (34) signal is unreliable signal (it is based on the early mechanism of a signal, from the fear that the target can not receive the signal will be triggered multiple times)
b, this signal is not generated in real time, and can not be queued so that the signal may be lost
c, in processing this signal can choose the default processing mode, you can also register a processing function (in some systems out of the function after the end of the return to the default processing mode)

3. Reliable Signal
A, [Sigrtmin,sigrtmax] signal within the range is a reliable signal
b, reliable signal support queuing, not lost, real-time generation
c, the communication between the process and the system is unreliable signal (when the system detects that the process is triggering some errors to send to the process is unreliable signal), in the Industrial control neighborhood generally use real-time signal

4, the source of the signal
Hardware: The operating system detects a hardware work exception and sends a signal to the process that is using the hardware
Software: A signal generated by a function or command such as kill, raise, alarm, etc.
Keyboard:
CTRL + C
Ctrl+\
CTRL + Z

5, the Signal processing method
1, ignore, do not do any processing
2. Terminate the process
3. Capture and Process:
Registers a signal processing function with the operating system before the signal occurs, and calls the function to process the signal after it has occurred
4. Terminate + produce core:
Core dump records memory usage and is written in core file, no core file is generated by default in Ubuntu system, need to be set by command (Ulimit-t Unlimited)
The core file is a binary file that requires the appropriate debugging tools to parse (GDB)
Gcc-g code.c->a.out
A.out An error occurred creating a core file
GDB a.out Core shows the code that generated the error

Second, signal
#include <signal.h>

typedef void (*sighandler_t) (int);

sighandler_t signal (int signum, sighandler_t handler);
function: Want the kernel to register a signal processing function
Signum: Signal to be processed
Handler
Function pointer: Indicates that the signal is captured and processed
Sig_ign: Tells the kernel not to send the signal to the current process, and if it is SIGCHLD, it also indicates that the child process of the current process is being reclaimed by init
Sig_del: Restore Default processing mode
Return value: How the signal is processed before the signal processing mode is set

Note: In some systems, the processing function of the signal can only be processed once, and the default processing will be restored after the processing function call ends, and if you want to persist, you need to register again at the end of the processing function.
SIGKILL, Stgstop signal can not be ignored, capture processing

Third, the signal processing of the sub-process
1. A child process created by fork inherits the signal processing of the parent process
2. Create a child process through the Vfork+exec function cannot inherit the signal handler function of the parent process, but will inherit the signal of the parent process is ignored

Iv. Sending signals
1. Keyboard:
CTRL + C
Ctrl+\
CTRL + Z
2. Error:
Except 0 (SIGFPE (8)) arithmetic anomalies
Invalid memory Access (SIGEGV (11)) segment error
Hardware failure (Sigbus (7)) Bus exception
3. Command
Kill-Signal Process number
Killall-Signal commands can send signals to multiple processes in bulk
4. Functions
int Kill (pid_t pid,int SIG);
Function: Sends a signal to the specified process

int Rais (int sig);
function: Send a signal to yourself

V. Pause
int pause (void);
Function: Causes the calling process to go to sleep until a signal terminates the process or the signal is captured

1, when the signal is triggered, the signal processing function will be executed first, pause and return
2, pause does not return (no signal trigger), or return-1 (signal generation and processing completed)

Six, sleep
#include <unistd.h>
unsigned int sleep (unsigned int seconds);
Function: Use the calling process sleep seconds seconds

1, when the process sleep seconds seconds after the signal generation and return
2, if it is due to sleep in the signal generation, then sleep will return the remaining number of seconds

Seven, Alarm
#include <unistd.h>
unsigned int alarm (unsigned int seconds);
Function: Use the calling process to receive SIGALRM signal after seconds

1, SIGALRM Default processing method is to terminate the process
2, if set again before the last SIGALRM signal generation, will return the remaining number of seconds
3. If you set the number of seconds to 0, the previous setting is canceled

Eight, signal sets and signal shielding
1, what is the signal set: the set of Signals sigset_t, composed of 128 binary, each of the binary represents a signal
#include <signal.h>
int Sigemptyset (sigset_t *set);
Function: Clear Signal set

int Sigfillset (sigset_t *set);
Function: Fill the signal set

int Sigaddset (sigset_t *set, int signum);
function: Adding signals to the signal set

int Sigdelset (sigset_t *set, int signum);
Function: Remove signal from signal set

int Sigismember (const sigset_t *set, int signum);
Function: Test signal Set whether there is a signal
Return value: Has return 1, no return 0, failed to return-1

2. Signal Shielding
Each process has a signal mask (signal mask), also known as a signal mask, which is a signal set that contains a signal that needs to be shielded
#include <signal.h>
int sigprocmask (int how, const sigset_t *set, sigset_t *oldset);
Function: Set the process new signal mask (signal Shield code), get the old signal shielding code
How to: Modify the signal mask
Sig_block: Adding a signal to the current signal mask
Sig_unblock: Removing a signal from the current signal mask
Sig_setmask: Old signal mask with new signal set
Newset: Newly added, deleted, replaced signal set, can also be empty, by how to decide
Oldset: Get the old signal mask
When Newset is empty, it is backing up the signal mask

Why signal masking:
When a process does not want to be disturbed (atomic operations) when performing some sensitive operations, but does not want the signal to be lost (ignored), the signal needs to be masked at this time
The purpose of shielding the signal is not to not receive the signal, but delay the reception, when the finished thing to do, should be the shielding signal to restore
The signal that occurs when the signal is screened is recorded once, the signal is set to a pending state, and once the signal screen is finished, it is sent again
Unreliable signal during signal shielding no matter how many times the signal is sent, the signal is unblocked and sent only once
Signals that occur during signal shielding are queued for reliable signals and processed individually after the signal contact is masked
When the signal processing function is executed, the current processing signal is blocked by default, and then restored after execution is completed.

int sigpending (sigset_t *set);
function: Get signal of pending status
The pending signals can be pre-searched before releasing the signal shield

Nine, signal processing
#include <signal.h>
int sigaction (int signum, const struct sigaction *act,struct sigaction *oldact);
Function: Can ignore signal, set or get signal processing mode
ACT: Set the signal processing mode of the heart
Oldact: Get the old signal processing mode

struct sigaction
{
void (*sa_handler) (int); Signal processing function pointers
void (*sa_sigaction) (int, siginfo_t *, void *); Signal processing function pointers need to send signals using Sigqueue
sigset_t Sa_mask; Signal shielding code, signals that are masked when the signal processing function is executed (when performing a signal processing function, the default mask is the function being processed, you can add other signals to be masked, and revert to the default after the signal processing function has ended)
int sa_flags;
Sa_nocldstop: Ignore SIGCHLD
Sa_nodefer/sa_nomask: Non-shielded signal during processing
Sa_resethand: After processing signal, restore default processing mode
Sa_restart: When the signal processing function interrupts the system call, the restart
Sa_siginfo: Processing signals with sa_sigaction
void (*sa_restorer) (void);//Reserved
};

int Sigqueue (pid_t pid, int sig, Const Union Sigval value);
Function: Sends a signal to the specified process and comes with some data

Ten, the timer
Three timers maintained by the operating system
Real timers: The actual time the program is running
Virtual timers: Log the time spent by the program in the user state
Utility Timers: Log the time spent by the program in the user state and kernel state
Real = practical + in/out consumption + hibernation

Use timers to do something, like the function of the alarm clock
#include <sys/time.h>
int Getitimer (int which, struct itimerval *curr_value);
Function: Gets the scheduled task set previously
Which: type of timer
Itimer_real true, signal: SIGALRM
Itimer_virtual virtual, signal: SIGVTALRM
Itimer_prof practical, signal: sigprof
Curr_value:
struct Timeval it_interval: time interval of clock signal
struct Timeval It_value: Time of first clock signal generation

struct Timeval
{
Long tv_sec; /* seconds */
Long tv_usec; /* microseconds */
};

int Setitimer (int which, const struct Itimerval *new_value,struct itimerval *old_value);
Function: Set, get alarm
New_value: New set of alarms
Null description can only be used to get old alarms
Old_value
Null description only set not get

Inter-process communication ******
First, the basic concept
interprocess communication (IPC): The process of exchanging data between processes is called interprocess communication
Ways to communicate between processes
Simple inter-process communication:
Command line: The parent process can append some data when it creates a child process through the EXEC function
Environment variable: The parent process creates a child process through the EXEC function by passing an environment variable table
Signals: Parent-child processes can send signals to each other based on process numbers for simple communication
File: A process writes data to a file, and another process reads it from a file
command line, environment variables can only be passed one way, the signal is too simple, file communication can not be real-time

Second, the pipeline
Traditional inter-process communication mode: pipeline
1, the pipeline is an ancient way of communication (basically no longer used)
2, the early pipeline is a half-duplex, and now most are full-duplex
3. Well-known pipeline (this kind of pipeline exists in file mode), suitable for communication between any process
To create a pipeline file:
Command Mkfifo
function Mkfifo
#include <sys/types.h>
#include <sys/stat.h>
int Mkfifo (const char *pathname, mode_t mode);
Programming mode for pipeline communication:
Process a process B
Create Pipeline Mkfifo
Open the pipe open pipe
Write/Read data read/write read/write Data
Close the pipe close close the pipe
Delete Unlink/remove
4, Nameless pipe: Created by the kernel, only the file descriptor of the pipeline is returned, the pipeline file is not visible, but this pipeline can only be used between parent-child processes created by fork
#include <unistd.h>
int pipe (int pipefd[2]);
Function: Returns two open pipe file descriptors
PIPEFD[0] used to read data
PIPEFD[1] used to write data

Iii. XSI IPC Inter-process communication
1, xsi communication is by the core of the IPC object to communicate
2, each IPC object has an IPC identifier (similar to a file descriptor), IPC identifier It is a non-0 integer
3, IPC objects must be created before the process gets, set, manipulate, delete, destroy
4, the creation of IPC objects must provide a key value (key_t), the health value is to create, obtain the IPC object basis
5, the method of generating health value:
Fixed literal value: 1980014
Use function calculation: Health value = Ftok (project path, Project ID)
Using macros to randomly assign the operating system: IPC_PRIVTE
The acquired IPC object identifier must be recorded to tell the other process
6. The IPC objects that XSI can create are: Shared memory, message queue, semaphore

Iv. Shared Memory
1, the kernel maintains a piece of shared memory area, the other process maps its own virtual address to this fast memory, and then can share this fast memory between multiple processes
2. The benefit of this interprocess communication is that information replication is not required and is the fastest way to communicate between processes
3, but this communication mode will face the problem of synchronization, need to cooperate with other communication methods, the most appropriate is the signal

Programming mode for Shared memory:
1, between the process to contract a key value
Process a process B
Create shared memory
Load shared memory load shared memory
Offload shared memory offload shared memory
Destroying shared memory

#include <sys/ipc.h>
#include <sys/shm.h>
int Shmget (key_t key, size_t size, int shmflg);
Function: Create shared memory (a piece of memory in the kernel), if the object you want to create already exists, you can make an error, or you can get
Size: Shared sizes, try to be multiples of 4096
SHMFLG:
Created: Ipc_creat | IPC_EXCL |0744
Return value: IPC object identifier (similar to file descriptor)

void *shmat (int shmid, const void *shmaddr, int shmflg);
Function: Load shared memory (the virtual address of the process and the shared memory mapping in the kernel)
return value of Shimid:shmget
SHMADDR: The virtual address provided by the process, and if NULL, the operating system automatically selects a block of address mappings
SHMFLG:
Shm_rdonly: Restrict memory permissions to read-only
Shm_remap: Mapping the existing shared memory
SHM_RND: Automatically assigned when SHMADDR is empty
The value of shmlba:shmaddr cannot be empty, otherwise an error occurs
0
Return value: The virtual address of the mapped memory
int SHMDT (const void *SHMADDR);
Function: Offload shared memory (the virtual address of the process is unmapped from the shared memory)

int shmctl (int shmid, int cmd, struct shmid_ds *buf);
Function: Control/Destroy Shared memory
Cmd:
Ipc_stat: Get the properties of shared memory
Ipc_set: Setting properties for Shared memory
IPC_RMID: Deleting shared memory
Ipc_info: Getting information about relational memory
BUF: An object that records shared memory properties

Note: Relational memory is the fastest form of inter-process communication because the data does not have a copy process, but the data is not written and read between processes, and other communication methods are required (signal)

Message Queuing is characterized by the ability to queue data and to accept messages by message type

Semaphores can be thought of as global variables shared between processes to manage the resources shared between processes

V. Message Queuing
1. Message Queuing is a data link table that is stored and managed by the system kernel and obtained through the IPC object identifier.
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int Msgget (key_t key, int msgflg);
Function: Create and get message queues
MSGFLG:
Created: Ipc_creat | ipc_exec | 0644
Gets: 0

int msgsnd (int msqid, const void *MSGP, size_t msgsz, int msgflg);
Function: Send message to Message queue
return value of Msgid:msgget
MSGP: First address of message (message type + message content)
Msgsz: Length of message memory (not including message type)
MSGFLG:
Msg_noerror: When the actual length of the message is longer than MSGSZ, then it is intercepted and sent according to the length of the MSGSZ, otherwise an error is generated.

ssize_t MSGRCV (int msqid, void *msgp, size_t msgsz, Long msgtyp,int MSGFLG);
Features: Accepting messages from Message Queuing
MSGP: Buffer for storing messages
MSGSZ: Message length to receive
Msgtyp: The type of message (it is contained in the first 4 bytes of a message)
MSGFLG:
Msg_nowait: If the message to be received does not exist, return directly, otherwise the message is blocked waiting
Msg_except: Receive the first message from the message queue for the first non-Msgtyp type

int msgctl (int msqid, int cmd, struct msqid_ds *buf);
Function: Control, destroy message queue
Cmd:
Ipc_stat: Get the properties of the message team
Ipc_set: Setting properties for Message Queuing
IPC_RMID: Deleting Message Queuing

Vi. IPC-related commands
Ipcs-m Find shared Content
IPCRM-M ID Delete shared memory
IPCS-Q viewing Message Queuing
IPCRM-Q ID Delete Message Queuing
Ipcs-s View Signal Volume
Ipcrm-s Delete semaphore

Seven, the signal volume
Semaphore (semaphore), which can be used as a global variable to be shared between processes and processes, and is typically counted for shared resources
How to use the semaphore:
1, process A, create semaphore, and set initialization (number of resources set)
2, Process B, get the semaphore, view the semaphore (query the number of remaining resources), reduce the amount of semaphore (use of resources), increase the semaphore (the resource is used to return)
3, when a process to try to reduce the semaphore, if not reduced, (the use of resources), the process can enter the waiting state, when the semaphore can be reduced (other processes to return the resources), the process will be awakened

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int Semget (key_t key, int nsems, int semflg);
Function: Create a semaphore or get a semaphore
Nsems: Amount of semaphore
SEMFLG:
Ipc_creat | ipc_exec | 0644

int semop (int semid, struct sembuf *sops, unsigned nsops);
function: Increase or decrease the amount of signal
struct SEMBUF
{
unsigned short sem_num; Semaphore/* Semaphore number */
Short Sem_op; Operation on Semaphore/* Semaphore operation */
Short SEM_FLG; Semaphore wait/* Operation flags */

}
Nsops: Number of operations

int semctl (int semid, int semnum, int cmd, ...);
Function: control or release of signal volume
Semnum: Number of semaphores
Cmd:
Ipc_set setting the properties of semaphores
Ipc_stat gets the properties of the semaphore
Ipc_rmid Delete semaphore
Ipc_info getting the semaphore information
Getval return Semaphore Quantity
Setval Set Semaphore Quantity
Return value: Amount of semaphore

UNIX Environment C language-process management, interprocess communication

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.