Programming for processes and Threads and Linux

Source: Internet
Author: User
Tags time 0

I. Overview

Process and thread there's a bunch of explanations on the network, I don't like plagiarism, and I don't like the idea of applying too much textbooks. In my own understanding of the process and the thread bar, of course, their own understanding is certainly not very rigorous, but the understanding should be faster than the textbook. Processes and threads can be considered concurrent execution programs, but only multi-processor multithreading can really achieve concurrency (multiple threads at the same time slice running concurrently), the other is not really real concurrency, are alternating on the CPU, but each program runs a short time (time slice), fast alternation, So it looks like it's running (concurrency) at the same time.

Almost the same effect, why is it divided into processes and threads? The biggest difference between a process and a thread is that the process and the process do not affect each other, they have their own complete virtual memory, is a complete individual. While threads exist in a process, a process can have many threads, and threads under the same process have a lot of shared memory, such as file descriptors, global variables, and their own private data, such as the memory of the stack area. So the overhead of creating a thread (the resource in possession) is much smaller than a single process, which is why the processes and threads are divided.

So summarize the relationship between the program and the process thread. A running program can have multiple processes, and a process can have multiple threads below it. This is the relationship between the three. To understand this concept more deeply, you have to understand it programmatically. Because of the relationship between theory and practice, Marx has discussed not to do.

Second, the concept

Process Number: A number that is used to mark a process.

Zombie Process: The child process is finished, but the parent process does not reclaim its resources, at which point the child process is a zombie process. Use the wait and WAITPID functions to solve this problem

Orphan process: The parent process has ended, but the child process is still running. The child process is the orphan process.

Daemon: A process that runs out of the terminal after it is run. The terminal switch has nothing to do with him.

PCB: Process Control block. The data structure that holds the management and control information for the process. It is the process management and control of the data structure, each process has a PCB, in the creation process, the establishment of the PCB, along with the process of running the process, until the end of the process and the end.

Status of the process: three-state model: ready, running, blocking (sleep)

Five-state model: slightly

Three, routines

① process: fork () Create a new process----> Run the parent-child process separately by the return value of the fork----> write the parent-child process separately----> The parent process waits for the child process to end the Recycle resource

② Thread: Create a new thread----> go to thread function execution----> main thread waiting to reclaim child threads

Routine Two: Create a new thread----> Detach thread----> Two threads without a single thread

Iv. process-related functions

1. header file

<unistd.h>,<sys/type.h>,<sys/wait.h>

2. View process commands under shell

#ps查看当前进程 #ps-ef #ps-ax View All Processes

Parameters: STAT: Current process state; TTY: Which terminal the process starts from; CMD: the command used to start the process

3. Type of process number

pid_t

4. Get the process number

pid_t getpid (void) Gets the current process process number

pid_t getppid (void) Gets the parent process number

pid_t getgdid (void) Gets the group process number

5. Start a new process

① is done by calling the system function, such as System ("PS &"), but this startup relies on the shell

② Create new by copying the current process

pid_t fork (void)

The child process starts after the fork function. This is a special function with two return values, the child process returns 0, and the parent process returns the PID (process number) of the child process. A large amount of data in a child process is replicated. such as file descriptors, process contexts, and so on. Only the process number, the timer, and so on, are unique to the child process.

6, the replacement of the process

Because a new process is obtained through replication of the process, but we tend to generate a process that needs to perform new tasks, so we need to replace the copied process and let him execute the program we want. Use the EXEC series function to perform the replacement process.

int execl (const char *path, const char *arg, ..., NULL);
int EXECLP (const char *file, const char *arg, ..., NULL);
int execle (const char *path, const char *ARG,..., Null,char * const envp[]);
int execv (const char *path, char *const argv[]);
int EXECVP (const char *file, char *const argv[]);
int execvpe (const char *file, char *const argv[],char *const envp[]);

Parameters: The path path (including executable file name) file current path executable file name argv executable option, example argv={"PS", "Ax", 0} Note last add 0

ENVP environment variable, the path that is searched by default. Example: wxvp[]={"path =/bin:/user", the function of a 0} colon is delimited, representing multiple default paths

7, process hangs (hibernate, blocking)

unsigned int sleep (unsigned int sec)

Two ways to lift a suspend: The specified time is up or the signal is received

8. Waiting for the process (also hangs)

The role is to wait for the child process to end and reclaim the child process's resources to avoid spawning the zombie process

①pid_t Wait (int *status)

Parameters: status, memory that holds the state of the child process can use three macros to read status wifexited (status) child process normal end is not 0 wexitstatus (status) Normal end returns the exit code wifstopped ( Status) is not 0 if terminated unexpectedly

Wait (NULL) if only the resource is recycled;

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

Wait for the corresponding PID subprocess to end the Reclaim space

Parameter: status equals the status of the previous function

pid:>0 when =-1 = 0 o'clock <-1

Options: Do not want to use the time 0

Five, thread-related functions

1. header file

<pthread.h> compile with-LPTHREAD option to connect to library

2. Thread Number Type

pthread_t

3. Creating thread Functions

int Pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*start_routine) (void *), void *arg);

Parameters: Thread the memory of the new thread number of the attr threading attribute struct-body address, default NULL Start_toutine thread function entry arg to the number of thread functions, no value is null

Return value: Success 0 Failure not 0

4. Blocking thread functions

int Pthread_join (pthread_t thread, void **retval);

Role: Wait for the child thread to end, and then exit the main thread. The child threads will all end when the main thread exits

RetVal The return value of the thread function

Return value: Success 0 failure: not 0

5. Separating thread functions

int Pthread_detach (pthread_t thread);

Function: The main thread end will end all child threads by default. After using this function, the main thread ends and no longer ends the child threads

Return value: Success 0 failure: not 0

6. Thread Exit Function

void Pthread_exit (void *retval);

retval variable address for storing thread function values

Return value: Success 0 Failure: errno

7. Cancel a thread that is executing

int Pthread_cancel (pthread_t thread);

You can cancel a thread. Threads can be canceled by default, but can also be set to not be canceled

8. Set whether the thread can be canceled

① whether the int pthread_setcancelstate (int state, int *oldstate) can be canceled;

State: Sets whether the pthread_cancel_enable can be canceled pthread_cancel_disable non-canceled

② whether to cancel the int pthread_setcanceltype (int type, int *oldtype) immediately;

Pthread_cancel_deferred not cancel immediately until cancel point cancellation (cancellation point including printf, etc.) pthread_cancel_asynchronous immediate cancellation

Return value: Success 0 Failure: errno

  9. Thread Cleanup function

  void Pthread_cleanup_push (void (*routine) (void *), void *arg);

void Pthread_cleanup_pop (int execute);

10. Initialize variables that describe thread properties

int Pthread_attr_init (pthread_attr_t *attr);

Parameters: Attr used to describe the properties of a thread

11. Cleanup and recycling of thread variables

int Pthread_attr_destroy (pthread_attr_t *attr);

Programming for processes and Threads and Linux

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.