#include <stdio.h> #include <unistd.h> static int idata = 111; int main() { int istack = 222; pid_t childPid; switch(childPid = fork()) { case -1: fprintf(stderr, "fork error."); break; case 0: idata *= 3; istack *= 3; break; default: sleep(3); break; } printf("PID = %ld, %s idata = %d istack = %d\n", (long)getpid(), (childPid == 0)?"(child) ": "(parent)", idata, istack); return 0; }
程序的输出结果表明,子进程在fork()时拥有了自己的栈和数据段拷贝,且对这些段中变量的修改将不影响父进程。