The process of programming Linux systems

Source: Internet
Author: User
Tags sleep function

The basic operations of file I/O have been summarized in the previous period, and today we continue to summarize the process operations of Linux system programming as I understand it.

First we understand a few concepts: program, process, thread.

The so-called program, which is a collection of computer instructions, is stored on disk as a file, a process is an execution activity of a program in its own address space. and Threads 进程内的一个执行单元,也是进程内的可调度实体 . Do you have any idea what you're saying? Anyway, the first time I heard this concept can be understood after the time to forget, and now I give you an example to help everyone understand, we all watch TV, the so-called program, is a script, like what "Journey to the World", "God of the Eagle" ... Many, here is not the introduction of TV, return to our theme, the program is a script, then the process is a specific film, such as the 86 version of the "Journey to the Monkey ", each play is compiled program execution, that is, the process. Some people will say, I do not like the 86 version of the "Journey to the monkey ", like to see the Jizhong version of the "Journey to the monkey " that this has a corresponding what? This is difficult not to pour the blogger, Bo Master on this issue, also did think, here I use C language development program, then someone learned Java, Python ... Well, the programs developed in different languages this corresponds to a different version of "Journey to the monkey ", we continue, then what is the thread? Our journey to the Monkey has many episodes, and our process is also made up of threads that are composed of multiple threads. That said, do not know people remember it? After you remember this, I still give them the concept and the difference between each other.

1. Concept:

Program: A program is a collection of computer instructions that are stored on disk as files.

Process: A process is an execution activity of a program in its own address space.

Threads: An execution unit within a process, which is also a scheduled entity within a process.

2. Contact:

1, a process is a dynamic execution of the program, the program is placed in the hard disk static, the process is to occupy the system resources are dynamically loaded into memory.

2, the process is the system of resource allocation and scheduling of the basic unit, is Operating System the basis of the structure. The thread thread, sometimes called a lightweight process, is the smallest unit of program execution flow.

3、一个线程可以创建和撤销另一个线程;同一个进程中的多个线程之间可以并发执行.

            4、相对进程而言,线程是一个更加接近于执行体的概念,它可以与同进程中的其他线程共享数据,但拥有自己的栈空间,拥有独立的执行序列。

    3、区别

    地址空间:线程是进程内的一个执行单元;进程至少有一个线程;它们共享进程的地址空间;而进程有自己独立的地址空间;

    资源拥有:进程是资源分配和拥有的单位,同一个进程内的线程共享进程的资源     线程是处理器调度的基本单位,但进程不是.     进程和线程二者均可并发执行.     简而言之,一个程序至少有一个进程,一个进程至少有一个线程.     线程的划分尺度小于进程,使得多线程程序的并发性高。     另外,进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率。     线程在执行过程中与进程还是有区别的。每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行,必须依存在应用程 序中,由应用程序提供多个 线程执行控制。     从逻辑角度来看,多线程的意义在于一个应用程序中,有多个执行部分可以同时执行。但操作系统并没有将多个线程看做多个独立的应用,来实现进程的调度和管理以及资源分配。这就 是进程和线程的重要区别。

区分了这三个重要概念以后,我们重点来看与进程有关的Linux/Unix系统API。

    1、创建子进程fork

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

    fork系统调用用于创建子进程,一个现存进程调用fork函数是UNIX内核创建一个新进程的唯一方法(这并不适用于交换进程、init进程和精灵进程。这些进程是由内核作为自举过程的一部分以特殊方式创建的)。由fork创建的新进程被称为子进程( child process)。该函数被调用一次,但返回两次。两次返回的区别是子进程的返回值是0,而父进程的返回值则是新子进程的进程ID。将子进程I D返回给父进程的理由是:因为一个进程的子进程可以多于一个,所以没有一个函数使一个进程可以获得其所有子进程的进程ID。fork使子进程得到返回值0的理由是:一个进程只会有一个父进程,所以子进程总是可以调用getppid以获得其父进程的进程ID (进程ID 0总是由交换进程使用,所以一个子进程的进程ID不可能为0)。

    下来我写个简单的程序测试一下这个API的用法:

#include <stdlib.h> #include <unistd.h>int main () {pid_t pid;    The fork is called once, returned two times, the child process returns 0, the parent process returns the child process ID, PID = fork ();        if (PID < 0) {printf ("NO child \ n");    Exit (1);    } else if (0 = = pid) {printf ("Child \ n");    } else {printf ("I am arent \ n"); } return 0;}

2, Vfork ()

       vfork同样是用来创建进程的,但是fork由细微的不同,  

1.vfork guarantees that the child process runs first, and the parent process may be scheduled to run after it calls exec or exit. If the child process relies on further actions of the parent process before invoking these two functions, it causes a deadlock.

2.fork to copy the process environment of the parent process, while Vfork does not need to fully copy the process environment of the parent process, the child process shares the process environment with the parent process before the child process calls exec and exit, and the parent process blocks the wait.

The same I give a simple test case:

 #include <stdio.h> #include <stdlib.h> #include <unistd.h> Int main () {    pid_t pid = -1;    pid =  Vfork ();     if (pid < 0)     {         printf ("vfork error\n");         exit (1);     }    else if (pid > 0)     {         printf ("i am parent\n");     }     else    {        sleep (10) ;         printf ("i am child\n");         exit (1);     }    return 0;} 

We can get from the results of the run, each time the child process is finished running, the parent process is running.

3, Getpid ()/getppid ()

Gets the current process ID and the parent process ID, which is the unique identity that identifies the process.

I also give a simple test case here:

#include <stdio.h> #include <stdlib.h> #include <unistd.h>int main () {     pid_t pid;    //fork is called once, returns two times, the child process returns 0, and the parent process returns the child process Id,    pid  = fork ();     if (pid < 0)     {         printf ("no  child \n");         exit (1);     }    else if ( 0 == pid)     {        printf ("I am Child \n" );         printf ("pid = %d\n", Getpid ());         printf ("ppid = %d\n", Getppid ());    }     else if  (pid > 0)     {         sleep (1);        printf ("i am parent \n");         printf ("pid = %d\n", Getpid ());         printf ("ppid = %d\n", Getppid ());     }    return 0 ;} Run result:                        [[email protected] Fork]# ./fork-2 I am  child pid = 6353ppid = 6352i am parent pid = 6352ppid =  3674

  

before moving on to the next system API, let's start with a few concepts: zombie process, orphan process, like a name, a zombie process is a child process

Orphan process: One parent process exits, and one or more of its child processes are still running, then those child processes will become orphans. The orphan process will be adopted by the INIT process (process number 1) and the Init process completes the state collection for them.

Zombie Process: A process uses fork to create a child process, and if the child process exits, and the parent process does not call wait or waitpid to get state information for the child process, the process descriptor of the child process is still stored in the system. This process is called a zombie process.

Before we use fork simple to create a process, after executing the program found that the child process and the parent process is not sequential, and is displayed separately, we can use the sleep function to prevent the orphan process, but this method is more expensive system resources to solve the orphan process and the zombie process, We're going to introduce several other api:wait ()/waitpid ()

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


The wait () function returns immediately after a call, blocking waits for any child process to exit. The call successfully returns the ID of this child process, and the call failed to return-1. The status of Wait () and the Waitpid function returns a value that tests its child process exit status with several macros.

Wait gets staus post-detection processing
Macro Definition Description
wifexited (status) Returns a non-0 value if the process child process ends normally
Wexitstatus (status) Returns the child process exit code if wifexited nonzero
wifsignaled (status) child process terminates because of a capture signal, returns a value other than 0
Wtermsig (status) if wifsignaled nonzero, returns the signal code
wifstopped (status) Returns a non-0 value if the process is paused
Wstopsig (status) if wifstopped nonzero, returns the signal code


#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include < Errno.h>int main () {    pid_t pid = -1,child_pid = -1;     int status;    pid = fork ();     if (pid < 0)     {        perror ( "fork ");         exit (1);    }     else if ( pid == 0)     {           printf ("i am child\n");    }     else if (pid > 0)     {         printf ("i am parent\n");         printf ("Child pid  = %d \n ", PID);  &Nbsp;      child_pid = wait (&status);         printf ("wait pid = %d\n", Child_pid);      The    //test subprocess returns the status         printf ("exit status =  %d\n ", wifexited (status));     }    return 0;}

The above code gives me the use of the Wait () function, as well as the basic usage of status, similar to the usage of several other macros, and does not give a few other uses.

For Waitpid () system calls,

The difference from the wait function is that waitpid is used to wait for the end of a particular process
Function Prototypes:
pid_t waitpid (pid_t pid, int *status, int options);
Parameters:
Status if not empty, the state information is written to the location it points to
Options allow changing the behavior of waitpid, the most useful option is Wnohang, which is to prevent waitpid from suspending the execution of the caller
Return value: Successful return of the PID waiting for subprocess, failure return-1

The above is the basic function of the process operation, the following will continue to summarize, through a comprehensive case to synthesize the use of these APIs.


The process of programming Linux systems

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.