2. parent and child

1.fork function

  (1) pid_t fork (void) ; all of the data to create a child process, the child process, the code is from the parent process to open up the chant. Failed to return -1, success, returns: returns the parent process ID of the child, the child returns 0. pid_t type indicates the process ID, but to -1 indicates that it is a signed integer (0 is not a valid process ID, the init process ID is the smallest, 1). The number of processes in the system to create a systematic resource decisions, no recovery process if the process exits after the resources, then this will be part of the resources has been occupied with.

  Process ID related functions:

  getpid () function; // Get the current process ID  pid_t getpid (void);

        ID // Get the current process of the parent process  pid_t GET PP the above mentioned id (void);

  getgid () function; // Get the current process using a user group ID  gid_t getgid (void);

        // Get the current process effective user group ID  gid_t GET E gid (void);

  getuid () function; // Get the current process actual user ID  the uid_t getuid (void);

        // Get the current process effective user ID  the uid_t GET E uid (void);

  Process of creation:

 

#include <sdtio.h>
#include <unistd.h>

int main ()
{
    pid_t id = fork();
    if(id == -1){
        perror("create fail:");
        return -1;
    }

    if(id == 0){
        the printf ( " The present process is the child process:% d ----- parent process ID:% D " , getpid (), getppid ());
    }
    if(id>0){
        the printf ( " The present process is the parent process:% d ----- subprocess ID: D% " , getpid (), ID);
    }
    while(1);
    return 0;
}

 

  Function is based on the distinction between a system function or a library function:

    1. Can access kernel data structures

    2. Can you access external hardware resources

  There is both arbitrary system function, it is not a library function.

  Commonly used to view the current system processes the command: ps aux

   Check how much the system can create process:

int main ()
{
    int number = 0;
    while(1)
    {
        pid_t pid = fork();
        if(pid<0)
        {
            perror ( " Failed to create " );
            sleep(1);
        }
        if(pid == 0){
            Exit ( - . 1 ); // child process exits 
        }
         IF (PID> 0 ) {
             // parent child process resource recovery 
            int Status;
            the wait ( & Status); // block until the child process exits 
            printf ( " Number The =% d \ the n- " , Number The ++ );
        }
    }
}

 

  Zombie process: after the child process exits, the parent process is not a child process of resource recovery, this time the child is a zombie process, be sure to avoid zombie, zombie process quantity is limited, there is the system of maximum resource decisions.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main ()
{
    pid_t pid = fork();
    if(pid ==0)exit(-1);
    if(pid>0)
    {
        while(1);
    }
}

 

  Orphan process: child process is still running, but the parent process to exit, and then this time the child is orphaned, orphaned system will not be affected, because the orphan process will be automatically recovered.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main ()
{
    pid_t pid = fork();
    if(pid == 0){
        while(1);
    }
    if(pid>0)
    {
        // parent process to exit 
        SLEEP ( 10 );
        exit(-1);
    }
    return 0;
}

 

  Process Exit: exit (-1);

  Process out of the way: automatically exit after one complete process run.

          2. Exit through exit (-1) process closes the file descriptor, empty the buffer

          3._exit () just off exit process, does not process the file descriptor, it will not clear the buffer.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("hello world");
    _exit(0);


    return 0;
}

  

(2) the parent and child after a fork (), what are the similarities and differences?

  View parent and child share data:

#include <sdio.h>
#include <unistd.h>

int main ()
{
    pid_t id = fork();
    if(id == -1){
        perror("create fail:");
        return -1;
    }

    if(id == 0){
        the printf ( " The present process is the child process:% d ----- parent process ID:% D " , getpid (), getppid ());
    }
    if(id>0){
        the printf ( " The present process is the parent process:% d ----- subprocess ID: D% " , getpid (), ID);
    }
    while(1);
    return 0;
}

#include <stdio.h>
#include <unistd.h>

int GData = 123 ; // global data segment --- 
int main ()
{
    int mydata = 123 ; // local data - stack space 
    
    pid_t PID = the fork ();
     IF (PID == 0 )
    {
        while(1)
        {
            // child process 
            printf ( " child process GData =% d mydata --- =% d " , GData, mydata);
            sleep(1);
        }
    }

    if(pid>0)
    {
        while(1)
        {
            printf ( " parent =% d mydata GData --- =% d " , GData, mydata);
            sleep(1);
            mydata++;
            gdata++;
        }
    }

    return 0;
}

 

    The same parts: global variables, .data, .text, heap, stack, environment variables, user ID, home directory, the working directory process, signal processing .....

    Different parts: Process ID, fork return value, both of the parent process ID, program run time, alarm clock (timer), the pending signal set.

    Parent and child share of the region:

      1. file descriptor

      2.mmap resume mapping area, after the fork, and his son has the execution order process is uncertain, depending on the scheduling algorithm used by the kernel of.

 

2.vfork () function

  fork () and vfork () is used to create the child process, after the vfork () ----- parent process to wait for the child process out of operation (copy-on-write), and the execution order of fork () and his son process It is determined by the dispatch system.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main ()
{
    pid_t pid = vfork();
    if(pid == 0){
        printf ( " the child \ the n- " );
         the while ( 1 );
    }

    if(pid>0){
        printf ( " parent \ the n- " );
    }
}

 

3.exec family of functions

  After the execution of (1) fork () to create a child process and the parent process is the same program (but there may be executing different code branches), the child tends to mobilize one kind exec function to execute another program. When a process call one of the exec function, the process is completely user-space code and data is replaced with a program, the startup routine from the new program begins execution. Call exec function does not create a new process, so the calling process ID before and after the exec function has not changed.

    The current process of .text, .data .text to be replaced with a loader, .data, and then let the process from the new .text the first instruction execution, but the process ID does not change, not just for nuclear shedding.

    exec function is as follows:  

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

  1.execlp function

    int execlp (const char * file, const char * arg ....); // load a process, with the PATH environment variable.

    Success: no return; failure: 1;

    Parameter 1: name of the program to be loaded, the function need to meet the PATH environment variable to use, when there is no parameter PATH 1 failed to return after all directory searches. This function is typically used to call the system program, for example: ls, date, cp, cat commands.

  2.execl function

    int execl (const char * path, const char * arg, ....); // load a process through: Path + name of the program to load

    Success: no return; failure: 1;

    Parameter 1: absolute path to load the program.

  3.execvp function

    int execvp (const char * file, char * const argv []); // load a process, using a custom environment variables env

    Success: no return; failure: 1;

    Parameter 1: The name of the program to be loaded, as the execvp and execlp principle, but with different parameters.

  Group general rule function 4.exec

    Once the call is successful exec function on the implementation of the new program immediately, no return values, error -1 is returned, so we usually directly in the exec () function call after call to perror direct () and exit (), do not need to if the judge.

l(list) Command line argument list
p(path) Use path variable when searching for file
v(vector) Using the command line parameter array
e(environment) Use environment variable array, NA original process environment variables, set the environment variable to run the new loader

  In fact the only real execve system call, the other five are ultimately a function call execve, the relationship between these functions as follows.

  

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main ()
{
    pid_t pid = fork();
    if(pid=0){
        char *const argv[]={"ls","-1","-a",NULL};
        execv("/bin/ls",argv);
        printf("********\n");
    }
    if(pid>0){
        printf("#######\n");
        while(1);
    }
    return 0;
}

 

PS: Where is wrong, please correct me, learn from each other.

Guess you like

Origin www.cnblogs.com/smallqizhang/p/12451982.html
Recommended