Process Control Fork and Vfork

Source: Internet
Author: User
Tags glob terminates

1. Process identifiers

The two basic identifier PID and PPID for the process described in the previous Process Description section will now detail the other identifiers of the process.

Each process has a non-negative shaping that represents a unique process ID. Once a process is terminated, its process ID can be used again. The following is the ID of a typical process and its type and functionality.

Process name: Swapper (Swap process), process id:0, type: System process, Function: It is part of the kernel, does not execute the program on disk, is the dispatch process.

Process name: init (init process), Process id:1, type: User process, Function: Never terminate, start system, read system initialization file.

Process name: Pagedaemon (page sprite process), process id:2, type: System process, Function: page operation of virtual storage system.

In addition to the process ID, there are some other identifiers for each process. The following functions return these identifiers:

1#include <sys/types.h>2#include <unistd.h>3pid_t Getpid (void);//return value: Process ID of the calling process4pid_t Getppid (void);//return Value: The parent process ID of the calling process5uid_t Getuid (void);//return value: The actual user ID of the calling process6uid_t Geteuid (void);//return value: The valid user ID of the calling process7gid_t Getgid (void);//return value: The actual group ID of the calling process8gid_t Getegid (void);//return value: The valid group ID of the calling process

The above 6 functions, if executed successfully, return the corresponding ID value, or 1 if it fails. In addition to the process ID and parent process ID, these two values cannot be changed, and the other 4 ID values can be changed under appropriate conditions. The following sample program is used to get the 6 ID values of the current process and print them out. We actually look at the code:

1#include <stdio.h>2#include <unistd.h>3#include <errno.h>4#include <stdlib.h>5 intMain ()6 {7 uid_t uid;8 uid_t Euid;9 pid_t pid;Ten pid_t ppid; OnePID =fork (); A  if(PID <0) -  { -printf"%d\n", errno); theExit2); -  } -  Else if(PID = =0){// Child -UID =getuid (); +Euid =Geteuid (); -printf"Child, pid:%d, Ppid:%d, uid:%d, Euid:%d\n", Getpid (), Getppid (), UID, euid); +Exit0); A  } at  Else{ -UID =getuid (); -Euid =Geteuid (); -printf"father-pid:%d, Ppid:%d, uid:%d, Euid:%d\n", Getpid (), Getppid (), UID, euid); -Sleep2); -  } in  return 0; -}

The program works as follows:

2. Actual Users and active users

(1) Actual user ID and actual user group ID: identify who I am. That is, login user uid and GID, such as my Linux with admin login, the actual user ID of all the commands running on Linux is the UID of admin, the actual user group ID is the GID of admin (can be viewed with the ID command).

(2) Valid user ID and valid user group ID: processes are used to determine our access rights to resources. In general, a valid user ID equals the actual user ID, and the valid user group ID equals the actual user group ID. When set-user-id (SUID) bit is set, the valid user ID equals the UID of the owner of the file, not the actual user ID; Similarly, if the set-user group-id (SGID) bit is set, the valid user group ID equals the GID of the file owner, not the actual user group ID.

Where the actual user ID/actual group IDs identifies who the process is (that is, the unique identity of the process in the system), the valid user ID/effective group ID/additional group IDs determine the access rights of the process
Suid (chmod u+s file) can only be applied to an executable file, allowing any user to execute the file as the owner of the file
Sgid (chmod g+s file) can only be applied to an executable file, allowing any user to execute the executable as a member of the owning group
Description: Suid and sgid indicate that when the bin is running, it will have the owner's permissions, in other words, as long as the executable program is run, the operator also has permission to operate on all relevant files of the owner (executable program reads and writes). Verification Code:

1#include <stdio.h>2#include <errno.h>3#include <string.h>4 #define_path_ "./log"5 intMain ()6 {7FILE *FP = fopen (_path_,"W");8  if(NULL = =FP) {9printf"Open File is the error, error code is:%d\n", _path_, errno);Ten  return 1; One  } A  Char*str ="This is a test\n"; -  intI=0; -   while(i< - ){ theFwrite (str,1, strlen (str), FP); -i++; -  } - fclose (FP); +  return 0; -}

3. Process Creation 3.1 fork () function creation process

The previous Process Description section briefly describes the creation of processes, creating sub-processes, respectively, through the fork () and Execve () functions, and further explores the problem of fork () creating child processes.

An existing process can call fork to create a new process. Return value: 0 is returned in the child process, the child process ID is returned in the parent process, and an error returns-1. As follows:

A child process is a copy of the parent process. For example, a child process obtains a copy of the parent process data space, heap, and stack (primarily a copy of the data structure). The parent-child process does not share these storage space portions. Parent-child processes share body segments. Since fork is often attributed to exec, many implementations now do not perform a full copy of the parent process data segment, stack, and heap. As an alternative, the write-time replication (Copy-on-write) technique is used. These zones are shared by parent-child processes, and the kernel changes their access to read-only. If any of the parent-child processes attempt to modify these zones, the kernel makes only one copy of the memory that modifies the zone.
The following program demonstrates the fork function, from which you can see that the changes made by the child process to the variable do not affect the value of the variable in the parent process.

1#include <unistd.h>2#include <stdio.h>3 intGlob =6;/*externalvariable in initialized data*/4 CharBuf[] ="a write to stdout\n";5 intMainvoid)6 {7  int var;/*automatic variable on the stack*/8 pid_t pid;9  var= the;Ten  if(Write (Stdout_fileno, buf,sizeof(BUF)-1) !=sizeof(BUF)-1) OnePerror ("Write Error"); Aprintf"before fork\n");/*we don ' t flush stdout*/ -  if(PID = fork ()) <0) -  { thePerror ("Fork Error"); -  } -  Else if(PID = =0) {/* Child*/ -glob++;/*Modifyvariables*/ +  var++; -  } +  Else { ASleep2);/*Parent*/ at  } -printf"pid =%d, Glob =%d, var =%d\n", Getpid (), Glob,var); -Exit0); -}

Execution and output: Generally speaking, the order of execution of the parent and child processes after the fork is indeterminate, depending on the kernel's scheduling algorithm. In the above program, the parent process is dormant for 2 seconds, so that the child process executes first.
The relationship between fork and I/O functions in the program: Write is not buffered (http://blog.sina.com.cn/s/blog_6fb9dec201017tk3.html) because write is called before the fork, So its data is only written to the standard output once. Standard I/O is buffered, if the standard output to the terminal device, then it is a row buffer, otherwise it is fully buffered. When you run the program interactively, only the lines that are output by printf are processed once, because the standard output to the terminal buffers is flushed by newline characters. When the standard output is redirected to a file, however, because the buffer is fully buffered and the newline character is not output, when fork is called, its printf data is still in the buffer, and the data is copied into the child process, and the buffer is copied into the child process. So the parent-child process has a standard I/O buffer with the row content, so each process terminates, it flushes the data in its buffer and gets the first printf output two times.

3.2 Fork File sharing features

One feature of fork is that all open file descriptors of the parent process are copied into the child process. Each of the same open descriptors for a parent-child process shares a file table entry. Suppose a process has three different open files, and when it returns from fork, we have the structure as follows:

There are two common scenarios for file descriptors that are processed after fork:
1. The parent process waits for the child process to complete. In this case, the parent process does not need to do any processing of its descriptors. When the child process terminates, the child process modifies the file offset to the update that was performed.
2. The parent-child process executes different procedural sections. In this case, after the fork, the parent-child process closes the file descriptor that they do not need to use, so that it does not interfere with the file descriptor. This approach is often used in the contact service process.
Differences between parent and child processes:
1. The return value of the fork;
2. Process ID is different;
3. Have a different parent process ID;
4. The Tms_utime, Tms_stime, Tms_cutime and Tms_ustime of the sub-processes are set to 0;
5. The file lock set by the parent process is not inherited by the quilt process;
6. The unhandled alarm of the child process is cleared;
7. The unhandled signal set of the child process is set to the empty.
Fork has the following two ways:
1. A parent process wants to replicate itself so that the parent-child process executes different pieces of code at the same time. For example, the parent process waits for a client request to generate a child process to process the request.
2. A process has to execute a different program. For example, after a child process returns from fork, call the EXEC function.
Reason for Fork call failure:
1. There are too many processes in the system;
2. The number of actual user processes exceeds the limit.

3.3 Vfork function

Vfork is used to create a new process, and the purpose of the new process is to exec a new program. Vfork and fork Create a new process, but it does not copy the address space of the new process into the child process, because the child process calls exec immediately and does not have access to the address space. Conversely, before a child process calls exec or exit, it runs in the space of the parent process, which means that the data segments, stacks, and heaps of the parent process are changed. The other difference between vfork and fork is that vfork guarantees that the child process runs first, and the parent process may be dispatched after it calls exec or (exit).
The following is a vfork application:

1#include <stdio.h>2#include <string.h>3#include <unistd.h>4#include <stdlib.h>5 intG_val =0;6 voidFun ()7 {8printf"Child exit\n");9 }Ten intMain () One { A  int_val =0; -pid_t ID =vfork (); -  if(ID <0 ){ theExit1); -  } -  Else if(id = =0){// Child - atexit (fun); +printf"This is the child process.\n"); -  //++g_val;//verify that the points are different +  //++_val; ASleep3); atExit0); -  } -  Else{ -printf"This is father process\n"); -  //printf ("Father exit, G_val =%d, _val =%d\n", G_val, _val); -  } in  return 0; -}

The visible child process directly alters the value of the parent process's variable because the child process runs in the address space of the parent process.

Process Control Fork and Vfork

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.