[Linux] Process (iv)--creation of a process

Source: Internet
Author: User
Tags function prototype glob sigint signal signal handler

11, Process creation

Linux process creation can be divided into two steps, the fork () and the Exec () function, fork () is responsible for creating a child process, and the parent process is only the PID ppid and some statistics, the EXEC () function is responsible for reading the executable file load address space run.


Fork () function prototype

pid_t fork (void); The child process returns 0, and the parent process returns the Pid,fork () function of the child process one time to create two returns.


Implementation of the fork () function
Fork () uses the technique of write-time copy (Copy-on-write), where the parent process and child processes have the same address space when the child process is created (these zones are set to read-only), and the parent process-related address space is copied only when the child process or parent process is writing the data. The parent-child process points to the same physical memory.
After fork () is whether the parent process executes first or the child process is indeterminate, the parent-child process created by the fork () function is a file table entry, and Linux implements the fork () function through the clone () system call.
Another way to create a child process is to call the Vfork () function, the difference between the vfork () and the fork () function is that the vfork () function does not copy the page table of the parent process, and the child process runs first in the address space of the parent process until the child process exits, and the parent process can continue to run. Another hidden danger of the vfork () function is that once a child process calls the Exec () function execution fails ....

Fork () Function Example:

[CPP]View Plaincopy
  1. #include <stdio.h>
  2. #include <signal.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include <errno.h>
  7. int glob = 5;
  8. Char buf[] ="A write to stdout\n";
  9. int main (void)
  10. {
  11. int var;
  12. pid_t pid;
  13. var = 88;
  14. if (Write (Stdout_fileno,buf, (sizeof (BUF)-1))! = (sizeof (BUF)-1))
  15. printf ("Write error\n");
  16. printf ("before fork\n");
  17. if ((PID = fork ()) < 0)
  18. {
  19. printf ("fork error\n");
  20. }
  21. Else if (pid = = 0)
  22. {
  23. glob++;
  24. var++;
  25. }
  26. Else
  27. {
  28. Sleep (2);
  29. }
  30. printf ("pid =%d,glob =%d, var =%d\n", Getpid (), Glob,var);
  31. Exit (0);
  32. }
  33. The output is as follows:
  34. ./a.out
  35. A write to stdout
  36. Before fork
  37. PID = 430,glob = 7, var = 89
  38. PID = 429,glob = 6, var = 88

[CPP]View Plaincopy
  1. The Vfork () sample program is as follows:
  2. #include <stdio.h>
  3. #include <signal.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8. int glob = 5;
  9. Char buf[] ="A write to stdout\n";
  10. int main (void)
  11. {
  12. int var;
  13. pid_t pid;
  14. var = 88;
  15. if (Write (Stdout_fileno,buf, (sizeof (BUF)-1))! = (sizeof (BUF)-1))
  16. printf ("Write error\n");
  17. printf ("before fork\n");
  18. if (PID = Vfork ()) < 0)
  19. {
  20. printf ("fork error\n");
  21. }
  22. Else if (pid = = 0)
  23. {
  24. glob++;
  25. var++;
  26. //exit (0);
  27. }
  28. Else
  29. {
  30. Sleep (2);
  31. }
  32. printf ("pid =%d,glob =%d, var =%d\n", Getpid (), Glob,var);
  33. Exit (0);
  34. }
  35. The function output is as follows:
  36. ./a.out
  37. Before fork
  38. PID = 29039,glob = 7,var =89
  39. The child process adds 1 to the variable. The result changes the value of the variable in the parent process because the child process is the same as the parent process's address space.

The instance program for parent-child process communication is as follows:

[CPP]View Plaincopy
  1. #define Recovery_api_version 2.3.1
  2. Const char* binary = "/tmp/update_binary";
  3. int pipefd[2];
  4. pipe [PIPEFD];
  5. Const char** args = (const char**) malloc (sizeof (char*));
  6. Args[0]=binary;
  7. Args[1]=recovery_api_version;
  8. Char *temp = (char*) malloc (10);
  9. sprintf (temp,"%d", pipefd[1]);
  10. Args[2]=temp;
  11. args[3]= (char*) path;
  12. Args[4]=null;
  13. pid_t pid = fork ();
  14. if (PID = = 0)
  15. {
  16. Close (pipefd[1]);
  17. EXECV (binary, (char*const*) args));
  18. printf (Exec child process error);
  19. _exit (-1);
  20. }
  21. Close (pipefd[1]);
  22. Char buffer[1024];
  23. file* from_child = Fdopen (pipefd[0],"R");
  24. while (fgets (buffer,sizeof (buffer), from_child)!=null)
  25. Char*command = strtok (buffer,"\ n");
  26. Waitpid (pid,&status,0)


Fork () function system call

The entry point for the fork () function system call is the Sys_fork () function, and ultimately the do_fork () function that calls the kernel (the function is architecture-independent)

[CPP]View Plaincopy
    1. Asmlinkage int sysfork ()
    2. {
    3. return Do_fork (sigchld,regs.regs->arm_sp,®s,null,null)
    4. }

As can be known from the above code, the SIGCHLD signal is sent to notify the parent process when the child process ends.

The Do_fork () function calls the Copy_process () function primarily, the copy_process () function returns a new task_struct struct, and the copy_process () function calls the Dup_task_struct () function, The child created at this time

The process and the original parent process have only one parameter, that is, Task_struct->stack,stack is usually saved in a union with Thread_info,

Process Environment:
Take the main () function of C as an example: the main () function is prototyped as follows:
int main (int argc,int *argv[]);
C program's storage space layout
Body segment BSS segment initialization data segment stack heap

Add: Exec Family functions

[CPP]View Plaincopy
  1. extern Char **environ;
  2. int execl (const Char *path, const char *arg, ...);
  3. int EXECLP (const Char *file, const char *arg, ...);
  4. int execle (const Char *path, const char *arg, ..., char * const envp[]);
  5. int Execv (const Char *path, char *const argv[]);
  6. int EXECVP (const Char *file, char *const argv[]);
  7. int Execve (const Char *filename, char *const argv[], char *const envp[]);
  8. The sample program is as follows:
  9. Example
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. int main ()
  13. {
  14. Execl ("/bin/ls","ls","-l", NULL);
  15. printf ("If execl execution fails, this will print out \ n");
  16. return 1;
  17. }



12, Kernel thread
12, Kernel thread
The kernel often needs to perform some operations in the background, kernel threads, which are standard processes running independently of kernel space, the difference between kernel threads and normal processes is that the kernel thread does not have a separate address space (in fact its mm pointer is set to NULL). They only run in kernel space, never switch to user space, kernel processes and normal processes can be scheduled, can be preempted, Linux does have some tasks to the kernel thread to do, such as Pdflush and ksoftirqd these tasks are obvious examples, Kernel threads can only be created by other kernel threads, and in general, kernel threads will always execute the functions that they get when they are created, unless the system restarts.

Creation of kernel Threads:
pid_t kernel_thread (int (*FN) (void *), void *arg, unsigned long flags)
Here's how to create a new kernel thread from an existing kernel thread:
struct task_struct *kthread_creat (int (*THREADFN) (void *data), void *data,const char namefmt[] ....);
The new thread will run the THREADFN function, pass the parameter to it as data, and the thread name NAMEFMT,
The newly created thread is in a non-operational state and is to be run by wake_up_process () or the following function
struct task_struct *kthread_run (int (*THREADFN) (void *data), void *data,const char namefmt[] ....)

Kernel thread exit:
The kernel thread starts running until the Do_exit () function is called, or the function int kthread_stop (struct task_struct *k) is called, and the argument passed to Kthread_stop is Kthread_creat () The address of the task_struct returned by the function


Instance:
Creating Threads

[CPP]View Plaincopy
    1. struct Task_struct *thread_task;
    2. int RC;
    3. Thread_task=kthread_create (Fsg_main_thread,common,"File-storage");
    4. if (Is_err (Thread_task))
    5. {
    6. rc = Ptr_err (thread_task);
    7. return err_ptr (RC);
    8. }
    9. Wake_up_process (Thread_task);

13, Process exit

Through the normal process end, through the signal, or through the call to the Exit function, regardless of how the process exits, the process ends with the help of the kernel function do_exit (in alps/kernel/kernel/ In exit.c), the process's resource reclamation is separated from the process descriptor collection, and the process descriptor is retracted after the wait () function of its parent process returns ~

Supplemental: UNIX Environment Process Exception exit situation
Below is a blog that references the following URLs: http://www.ibm.com/developerworks/cn/aix/library/1206_xiejd_unixexception/
Process exceptions can be broadly divided into two categories:
One: Sending a signal to the process causes the process to exit abnormally
Two: The code itself error causes the process to exit
First class: Sending a signal to a process causes the process to exit:
(1) Sending a signal to the process causes the process to exit, the process receives a signal may cause the process to exit and produce a coredump file, in the UNIX environment there are three ways to send the signal to the target process, causing the process to exit unexpectedly.
Mode one: Call function Kill () send signal, prototype is int kill (pid_t pid,int Sig)
The following code is the sample code:

[CPP]View Plaincopy
  1. 1 #include <sys/types.h>
  2. 2 #include <signal.h>
  3. 3
  4. 4 int main (int argc, char* argv[])
  5. 5 {
  6. 6 char* pid = argv[1];
  7. 7 int pid = atoi (PID);
  8. 8
  9. 9 Kill (PID, SIGSEGV);
  10. return 0;
  11. 11}


Mode two: Run the kill command to send a signal
Format is Kill Sigxxx PID
Mode three: Use the keyboard to send signals at the terminal
Using Control-c to send a SIGINT signal, using control-\ to send a sigquit signal, using control-z to send a SIGTSTP signal, how to prevent this kind of signal arrival cause signal exit? By calling the signal function to bind the signal handler to deal with the arrival of the signal void (*signal (int sig, void (*func))) (int)), insert the following code to achieve the shielding signal SIGINT effect (void) signal (S Igint, sig_ign);
Class II: Programming errors cause the process to exit abnormally
When the process performs an illegal operation, the computer throws a processor exception, which refers to the soft interrupts, which is the processor exception caused by the illegal operation of the process, which is a synchronous exception caused by the illegal operation of the process, such as memory protection exception, except 0 exception, missing pages exception, and so on. The system assigns exception handlers to each exception, and invokes the corresponding exception handler when there is an exception.
Example Analysis:
(1) Invalid memory Access instance

[CPP]View Plaincopy
    1. 1 #include <stdio.h>
    2. 2 int main ()
    3. 3 {
    4. 4 char* str = "Hello";
    5. 5 Str[0] = ' H ';
    6. 6 return 0;
    7. 7}


(2) Except 0 exceptions

[CPP]View Plaincopy
    1. 1 #include <stdio.h>
    2. 2
    3. 3 int main ()
    4. 4 {
    5. 5 int a = 1, b = 0, C;
    6. 6 printf ( "Start running\n");
    7. 7 C = A/b;
    8. 8 printf ( "About to quit\n");
    9. 9}


How to debug a problem with a process exception
(1) Analyze the cause of abnormal exit using Coredump file

[Linux] Process (iv)--creation of a process

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.