首页 > 其他 > 详细

fork() 函数的使用

时间:2021-07-14 10:23:17      阅读:34      评论:0      收藏:0      [点我收藏+]
#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()时拥有了自己的栈和数据段拷贝,且对这些段中变量的修改将不影响父进程。

fork() 函数的使用

原文:https://www.cnblogs.com/donggongdechen/p/15009239.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!