"Linux" multi-process programming

Source: Internet
Author: User
Tags erro

I. Process Fundamentals
    • process : A process is the concept of an operating system, and whenever we execute a program, a process is created for the operating system, along with the allocation and release of resources. A process can be thought of as a process of execution of a program.
    • the difference between a process and a program :
    1. When the program is static, it is an ordered set of instructions saved on disk, without any concept of execution.
    2. A process is a dynamic concept that is the process of program execution, including creation, scheduling, and extinction.
    • The process is represented in the operating system : Task_struct, the process is described by a struct called task_struct, also called the Process Control block PCB, which means that each process in Linux corresponds to a task_struct struct. The structure records everything about the process.
    • files in the Linux process : Each process in the Linux operating system has two data structures describing file-related information.
    1. First: Fs_struct, which contains the current working directory and root directory of this process, umask. Umask is the default mode in which new files are created, which can be changed by a system call.
    2. The second: Files_struct, which contains information about all the files that this process is using. The F_mode field describes what mode the file was created in: read-only, read-write, or write-only. F_pos saves the location where the next read or write in the file will occur. F_inode describe the VFS index node of a file, whereas F_ops is a pointer to a routine vector, each representing a function that wants to be applied to the action of the file.
    • run-time structure of the process : (Excerpt from Vamei blog, http://www.cnblogs.com/vamei/archive/2012/10/09/2715388.html)

    • View process information : such as PS and other commands
Second, Process Control

Linux environment, there are two basic operations for creating and modifying processes: the function fork () is used to create a new process, which is almost a full copy of the current process, and the function family exec () is used to start another process to replace the currently running process.

2.1 Fork System call

Defined as follows:

#include <sys/types.h>#include<unistd.h> pid_t fork (void);

The call to the function returns two times, the PID of the child process is returned in the parent process, and 0 is returned in the child process to determine whether the current process is a parent or child process. When the fork call fails, return-1. and set the errno.

The fork function copies the current process, creates a new process table entry in Task_struct, and many properties are copied from the parent process, using the "copy-on-write" technique, while the file descriptor opened in the parent process is also open in the child process, and the counter is incremented by 1.

Sample code: From http://blog.csdn.net/jason314/article/details/5640969

/** FORK_TEST.C * Version 1 * Created on:2010-5-29 * author:wangth*/#include<unistd.h>#include<stdio.h>intMain () {pid_t fpid;//Fpid represents the value returned by the fork function    intCount=0; Fpid=Fork (); if(Fpid <0) printf ("Error in fork!"); Else if(Fpid = =0) {printf ("I am the child process and my process ID is%d/n", Getpid ()); printf ("I am father's son/n");//for some people, Chinese looks more straightforward. count++; }    Else{printf ("I am the parent process, my process ID is%d/n", Getpid ()); printf ("I'm a child, his father/n"); Count++; } printf ("The statistical result is:%d/n", Count); return 0;}
2.2 exec function Family

The system call EXECVE () replaces the current process with a specified program whose parameters include the file name (filename), the argument list (argv), and the environment variable (ENVP). The EXEC function family is of course more than one, but they are roughly the same, in Linux, they are: Execl,execlp,execle,execv,execve and EXECVP.

Once a process calls the Exec class function, it is itself "dead", the system replaces the code snippet with the new program's code, discards the original data segment and stack segment, and assigns new data segment and stack segment to the new program, the only one left is the process number, that is, for the system, or the same process, But it's already another program.

So what if my program wants to start another program's execution but I still want to run it? That is the use of the combined fork and exec. The following code shows how to start running other programs:

Example:

Charcommand[ the];voidMain () {intRtn/*The return value of the child process*/         while(1) {                /*read the command to execute from the terminal*/printf (">" ); Fgets (Command, the, stdin); Command[strlen (command)-1] =0; if(fork () = =0 ) {                       /*the child process executes this command*/EXECLP (command, command); /*if the EXEC function returns, indicating that the command is not executed correctly, print the error message*/perror (command);                Exit (Errorno); }                Else {                       /*The parent process waits for the child process to end and prints the return value of the child process*/Wait (&RTN); printf ("Child process return%d/n",. Rtn); }        }}
Third, process communication

We know more, the address space between processes is relatively independent. Processes and processes cannot communicate with each other through global variables as between threads. If you want to communicate between processes, you need other mechanisms.

Commonly used inter-process communication methods have these kinds of

    • Traditional interprocess communication: nameless pipe (pipe), well known pipe (FIFO) and signal (signal)
    • System v IPC objects: Shared memory (Share memories), message queues, and semaphores (semaphore)
    • BSD: Socket (socket)
3.1 Pipeline Communication

A pipeline is a method of communicating based on a file descriptor. When a pipeline is established, it creates two file descriptors fd[0] and fd[1]. where fd[0] is fixed for read pipelines, while fd[1] is fixed for write pipelines , general file I/O functions can be used to manipulate pipelines (except Lseek).

Example: The parent process writes data to the pipeline, and the child process reads the data from the pipeline "Hello World"

#include <fcntl.h>#include<stdio.h>#include"apue.h"#include<errno.h>#include<sys/wait.h>#include<sys/types.h>#include<unistd.h>#include<stropts.h>#include<sys/mman.h>intMain (intARGC,Char*argv[]) {    intn,fd[2];    pid_t pid; CharLine[maxline]; if(Pipe (FD) <0) Err_sys ("Pipe Err"); if((Pid=fork ()) <0) Err_sys ("Pipe Erro"); Else if(pid>0) {Close (fd[0]); if(Write (fd[1],"Hello world \ n", -) <0) Err_sys ("Write Err"); }    Else{Close (fd[1]); if((N=read (fd[0],line,maxline)) <0) Err_sys ("Read Erro"); if(Write (Stdout_fileno,line,n) <0) Err_sys ("Write Erro"); } exit (0);}
3.2 Signal Volume

Recommended Blog: http://blog.chinaunix.net/uid-26833883-id-3228615.html

3.3 Shared Memory

Recommended Blog: http://blog.chinaunix.net/uid-26833883-id-3230564.html

Introduction to Shared Memory:

    • Shared memory is the most efficient way to communicate between processes, and processes can read and write directly to memory without requiring any copy of the data.
    • In order to exchange information between multiple processes, the kernel specifically leaves out a chunk of memory that can be mapped to its own private address space by the process that needs to be accessed. The process can read and write directly to this piece of memory without having to copy the data, thereby greatly improving efficiency.
    • Because multiple processes share a piece of memory, you also need to rely on some kind of synchronization mechanism.

Operation Flow:

<1> Create/Open Shared memory

<2> mapped shared memory, which maps the specified shared memory to the process's address space for access

<3> Undo Shared Memory Mappings

<4> Delete Shared memory objects

Related API:shmget,shmat,shmd,shmctl.

3.4 Message Queuing

Iv. references

Process Basics Http://www.cnblogs.com/vamei/archive/2012/10/09/2715388.html

From program to process http://www.cnblogs.com/vamei/archive/2012/09/20/2694466.html

Inter-process Pipeline communication http://blog.chinaunix.net/uid-26833883-id-3227144.html

author : Simandou XIAOP

Source : http://www.cnblogs.com/panweishadow/

For non-commercial purposes, you are free to reprint, but please retain the original author information and article link URL.

"Linux" multi-process 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.