Linux Multi-process programming

Source: Internet
Author: User
Tags signal handler terminates

The core concept in the operating system is the process: This is an abstraction of the running program.
A process is a type of activity that has programs, inputs, outputs, and states. A single processor can be shared by a number of processes, and it uses some scheduling algorithm to schedule the process. Note: If a program runs two times, it is two processes.


Process Creation Fork

#include <sys/types.h> #include <unistd.h>pid_t fork (void): Returns 2 times per call, returns a child process PID in the parent process, returns 0 in the child process, returns 1
The fork function copies the current process and creates a new process table entry in the kernel process table. The new process table entry has the same properties as the original process, such as heap pointers, stack pointers, and flag register values. There are also many new properties that are changed, such as the ppid of the process is set to the PID of the far process, the signal is cleared (the signal processing function is no longer working for the new process)


EXEC series functions

#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[]); in T EXECVP (const char *file, char *const argv[]); int execve (const char *path, char *const argv[], char *const envp[]);

The path parameter specifies the full path to the executable file, which can receive a file name, and the location of the file is found in the environment variable path. Arg accepts mutable arguments, argv accepts parameter arrays, and they are passed to the main function of the new program. ENVP is used to set the environment variable for the new program, and if it is not set, the new program uses the environment variable specified by Environ.

In general, the EXEC function is not returned unless an error occurs. Return 1 On Error and set errno, the code after calling exec in the original program will not execute after the call succeeds, because the source program has been completely replaced (code and data) by the program specified by the EXEC parameter.

The EXEC function does not close open file descriptors in the source program unless the file descriptor is set to Sock_cloexec


Handling Zombie Processes

For multi-process programs, the parent process generally needs to track the exit status of the child process. Therefore, when the child process finishes running, the kernel does not immediately release the process's process table entry to satisfy the parent process's subsequent query on the child process exit information. After the child process finishes running, the parent process reader exits the state, which we call the child process in zombie state. If the parent process ends or terminates abnormally, and the child process continues to run, the ppid of the child process is set to 1, the init process. The init process takes over the child process and waits for it to end.

Child processes stay in the zombie state, occupying the kernel resources, which is absolutely not allowed, after all, the kernel resources are limited. The following function is called in the parent process to wait for the child process to end and to get the return information of the child process, thus avoiding the generation of the zombie process or ending the zombie state of the child process immediately:

#include <sys/types.h> #include <sys/wait.h>pid_t wait (int*status);p id_twaitpid (pid_t pid, int *status, int options);

The wait function will block the process until one of the process's child processes has finished running. It returns the PID of the child process that is running and stores the exit state information for the child process in the memory pointed to by the status parameter.

Waitpid waits only for the child process specified by the PID parameter, if the PID value is-1, the same as the wait function, that is, waiting for any one child process to end. The options parameter can control the behavior of the waitpid, and when the parameter is Wnohang, Waitpid will be non-blocking: If the target child process specified by the PID has not ended or terminates unexpectedly, WAITPID returns 0 immediately, if the target child process does exit normally, Then Waitpid returns the PID of the child process. Failed to return 1, and set errno.

To perform a non-blocking call if the event has already occurred, you can increase the efficiency of the program. For the Waitpid function, we'd better call it after a child process exits. So how did the parent process know that a child process has exited? This is exactly what the SIGCHLD signal is used for. When a process is finished, it sends a SIGCHLD signal to its parent process. Therefore, we can capture the SIGCHLD signal in the parent process and call the WAITPID function in the signal handler to completely end a child process. As shown below:

The static void Handle_child (int sig) {pid_t Pid;int stat;while (pid = Waitpid ( -1, &stat, Wnohang)) > 0) {/* to the end of the child process is good Post process */}}

Pipeline

Pipelines are a common means of communication between parent and child processes, and pipelines can pass data between parents and sub-processes, using the two pipe file descriptors (Fd[0] and fd[1]) that are open after the fork is called.

Pipeline has a pipe function to create, at this time the pipeline is unidirectional, pipe function explanation see: Network Programming api-(Advanced I/O function)

Examples of piping programs :

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys /types.h> #define ERR_SYS (msg) do {perror (msg); exit ( -1),} while (0) int main (void) {int pipefd[2];p id_t pid;if (pipe ( PIPEFD) < 0) Err_sys ("pipe"), if ((Pid= fork ()) < 0) Err_sys ("fork"), else if (PID = = 0) {char buf[10] = {0};close (pipefd[ 1]); Read (pipefd[0], buf, sizeof (BUF)); When there is no data in the pipeline, read blocks printf ("in Child process:\n");p rintf ("    %s\n", buf); exit (0);} Else{close (pipefd[0]); sleep (1); write (pipefd[1], "Hello", strlen ("Hello"); wait (NULL);} return 0;}

Reference:

1, "Linux High Performance Server Programming" 9 chapters multi-process programming/pipeline

2. Network Programming api-(Advanced I/O functions)

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.