10 Process Control 1

Source: Internet
Author: User
Tags unique id

Concept

Program: A file stored on disk that specifies the code to be executed and the action to be performed when it is run.

Process: The process of loading a program into a piece of data in memory, the process of executing a program, producing, developing, and dying.

Threads: Unix's smallest dispatch unit, a process can have multiple threads, share process IDs, and share process resources.

Parent-child processes

Processes are managed by a tree structure, and when one process starts another, the process that is started is the child process, the original process being the parent process.

Fork (): Copies the data of the parent process, the stack segment, and the process environment. In addition, each sub-process has its own process environment

Init process: Parent process for all processes

Process status

Operating state: allocated to the CPU

Ready state: Waiting for CPU

Sleep state: Cannot get CPU until something happens, enters ready state

Process Property Functions:

Process identifier PID: Unique ID number of the process

pid_t getpid () Get process ID

pid_t Getppid () Gets the parent process ID

pid_t getpgrp () Gets the process group ID

Process user identification number

uid_t Getuid () returns the user ID (UID: User ID) of the process

uid_t Geteuid () returns the valid user ID of the process (which permissions the process has)

gid_t Getgid () returns the group ID of the process

gid_t Getegid () returns the valid group ID of the process

chmod u+s Uid_demo? The person who runs the program, temporarily owns the user rights of the file owner while the program is running.

Process Call

To create a new process step

1. Fork () to create a new process that enables replication of the current process

2.exec () library modifies the process created to create the process in order to run the new program, after modifying the child process through the EXEC function family, let the child process execute the new program

Create a new Process pid_t fork ()

<sys/types.h>

<unistd.h>

In the parent process, the child process PID is returned, and the child process returns 0

Example

void Testfork ()

{

pid_t Pid=getpid ();

pid_t Ppid=getppid ();

printf ("Proc id:%d\n", PID);

printf ("Parent proc:%d\n", ppid);

Create a process

pid_t pt=fork ();

Creation failed

if (pt<0)

{

Perror ("Fail fork");

}

Child process

else if (pt==0)

{

printf ("This is a chinld produce!id:%d\n", Getpid ());

}

Parent process

Else

{

printf ("This is a parent produce!id:%d\n", Getpid ());

}

printf ("Test")

}

Analytical:

The parent-child process shares the resource. When fork () is used, the following code is available for both parent and child processes. Then printf ("test") will output two times.

After the fork () call, if the creation fails, that is pt<0;

If successful, start the parent process first, or else

{

printf ("This is a parent produce!id:%d\n", Getpid ());

}

Then it will go down to the execution, printf ("Test") .... , the parent process will not end until exit () or _exit () or return or EXEC function families.

The child process is not executed until the parent process is finished, else if (pt==0)

{

printf ("This is a chinld produce!id:%d\n", Getpid ());

}

The resource is shared as it continues down the execution. So it will also output printf ("test");

So fork causes the child process to replicate all the resources of the parent process, which is a bit redundant and can use Vfork ().

Vfork ()

Sometimes, a child process is created in order to run other programs without duplicating the resources of the parent process.

Vfork Share Parent-child process resources. After the call, the parent process blocks until the child process calls exec () or _exit ();

Note: You cannot return with return, or exit ()!

Difference:

Exit _exit return

_exit (): Exit directly, do not close the file, do not clean I/O

Exit (): Close the file, clean I/O before terminating the process

Return: Release handle, variable, popup function call buyers, go back to upper level function

Atexit () registered callback function is called before exit and return exits

In C + +, return invokes the destructor of the local object, exit, _exit does not

It is recommended to use fork (),

Write-time copy mechanism (Copy-on-write COW)

The fork () function needs to replicate the resources (variables) of the parent process

At the beginning of the creation, the related resources are not copied

Access the same physical memory if only the value is read

Once the write operation is made, the resource is copied and then written

Example:

String str1= "Hello World";

String str2=str1;

printf ("str1 ADRR:%p", Str1.c_str ());

printf ("str2 ADRR:%p", Str2.c_str ());

At this point the STR1,STR2 address is found to be the same. Even if the STR1,STR2 is two different variables.

Modify:

str1[0]= ' H ';

printf ("str1 ADRR:%p", Str1.c_str ());

printf ("str2 ADRR:%p", Str2.c_str ());

At this point the address of STR1,STR2 will become different.

This is the write-time copy mechanism, which is copied only when it is modified.

function families

exec function cluster. Executes another program as a subprocess of the original process

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, const char **ARGV)

int EXECVP (const char* file, const char **ARGV)

int Execve (const char* path, const char **ARGV, char *const envp[])

Analytical:

EXECL: The entry parameter is a variable parameter list (one-level pointer), ending with NULL

EXECV: The argument is an array of parameters (level two pointers)

P Suffix: Search environment variable PATH, find executable file

E suffix: Explicit pass-through environment variables

Note: After the EXEC function call succeeds, the system will replace the address space of the new program with the address space of the calling process and load the new program contents.

Example:

void Testexec ()

{

pid_t pid=fork ();

if (pid==0)

{

printf ("This is a child:%d", getpid ());

The first parameter requires a full path

Execl ("/bin/ls", "ls", "-l", NULL);

Or the following two sentences instead

char *buf[128]={"ls", "-ls"};

Execl ("/bin/ls", buf, NULL);

Only need name

EXECLP ("ls", "ls", "-l", NULL);

printf ("End");

}

Else

{

printf ("This is a parent:%d", getpid ());

}

}

Analytical:

The main function of the EXEC function cluster is to jump.

Immediately jump to the list of output LS.

Execl ("/bin/ls", "ls", "-l", NULL);

And the code down will not execute.

printf ("End"); not output.

Of course, you can also jump to other programs that you wish to customize.

EXECLP ("./mian2", "./main2", NULL);

Environment variables

Way One:

ENV command: Displays all environment variables for the current user

Export command: Modify or display all environment variables for the current user

Expote |grep: Querying specified environment variables

unset command: Delete an environment variable [unset AAA]

Use the command directly at the terminal:

Set environment variables: Expoet aa= "AAAAA";

Modify environment variables: Expoet aa= "BBBBBB";

Query Aa:expote |grep AA

Remove Aa:unset AA

Way two:

extern Char **environ

Array of environment variable pointers in UNIX systems

Example:

Iterate through all the environment variables

extern char * * environ;

Char **p=environ;

while (*P)

{

printf ("%s\n", *p);

++p;

}

Way three:

Header Files <stdlib.h>

char* getenv (char *name)

Gets the environment variable value, NONE returns null

int putenv (const char *expr)

Set/Modify environment variables, Name=value,

Delete environment variables only if name is passed

Example:

Setting environment variables

Putenv ("Abc=hello World");

pid_t pid=fork ();

if (pid==0)

{

printf ("This is child,abc=%s\n", getenv ("ABC"));

}

Else

{

printf ("This is parent,abc=%s\n", getenv ("ABC"));

Usleep (500);

}

Delete environment variables

Putenv ("ABC");

printf ("abc=%s\n", getenv ("ABC"));

10 Process Control 1

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.