This is an exercise in "APUE" chapter 8(exercise 8.2, 2th edtion). The all discription is:
Recall the typical arrangement of memory in Figure 7.6. Because the stack frames corresponding to each function call are usually stored in the stack, and because after a vfork the child runs in the address space of the parent, what happens if the call to vfork is from a function other than main and the child does a return from this function after the vfork? Write a test program to verify this, and draw a picture of what’s happening.
In my program:
static void f1(void), f2(void);
int main(void) {
printf("main address: %d\n", main);
f1();
f2();
_exit(0);
}
static void f1(void) {
printf("f1 address: %d\n", f1);
pid_t pid;
if ((pid = vfork()) < 0)
err_sys("vfork error");
}
static void f2(void) {
printf("f2 address: %d\n", f2);
char buf[1000];
int i;
for (i = 0; i < sizeof(buf); ++i)
buf[i] = 0;
}
I run the program, the output is:
main address: 4196560
f1 address: 4196604
f2 address: 4196663
f1 address: 4196604
[1] 12929 segmentation fault ./a.out
I am confused about the output.
- print
f1 address: xxx
, we call vfork(), the child process runs first. - print
f2 address: xxx
, then child process calls _exit(0). - main progress return from f1(), the stack frame of f1 was changed by f2, it may result segmentation fault.
But why print f1 address: 4196604
twice and why the address of f1 and f2 are not same?
According to
vfork
documentation, you should not return from current function.Also, please note that:
Since
vfork
does not copy the page tables from the parent, it makes a lot of sense not to return from current function. When the child exits it will mess up the stack frame from the parent.You can also view the following answer