Fork and process address space

Source: Internet
Author: User

 

The address space of a process is independent of each other. That is to say, each process has its own page Directory and page table. Once fork () is called, the address space of the Parent and Child processes is two spaces. If the child process modifies some of the memory, the parent process cannot be seen. For example, the following test:

# Include <stdio. h>

# Include <sys/types. h>

# Include <unistd. h>

Struct xx

{

Int;

};

Int main ()

{

Pid_t pid;

Struct xx s;

S. a = 5;

Struct xx * sp = & s;

Pid = fork ();

If (pid> 0)

{

Printf ("parent show % p, % p, a = % d \ n", sp, & sp-> a, sp-> );

Sp-> a = 4;

// While (sp-> a> 0 );

Sleep (10 );

Printf ("parent show % p, % p, a = % d \ n", sp, & sp-> a, sp-> );

Printf ("parent exit \ n"); // exit (0 );

}

Else

{

// While (sp-> a = 5 );

Printf ("child show % p, % p, a = % d \ n", sp, & sp-> a, sp-> );

Sp-> a =-1;

Printf ("child change a to % d \ n", sp-> );

}

Return 0;

}

The compilation and running result is:

[Root @ 141 test] # gcc test. c

[Root @ 141 test] #./a. out

Parent show 0x7fffe86b64a0, 0x7fffe86b64a0, a = 5

Child show 0x7fffe86b64a0, 0x7fffe86b64a0, a = 5

Child change a to-1

Parent show 0x7fffe86b64a0, 0x7fffe86b64a0, a = 4

Parent exit

Everything is clear ~

After a one-night project was called, the Parent and Child processes encountered a problem. Basic knowledge is still very important!

 

This article is from the blog "Xiaoqiang technology blog ".

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.