免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2788 | 回复: 3
打印 上一主题 下一主题

[函数] 关于fork函数的用法,动态分配内存怎么用?(简单的) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-12-07 19:30 |只看该作者 |倒序浏览
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>

void sig_child(int signo)
{
    while(waitpid(-1, NULL, WNOHANG) > 0);
}

int main(int argc, char **argv)
{
    int aa = 10;
    int pids[100] = {0};
    int index = 0;

    signal(SIGCHLD, sig_child);

    char *hello = (char*)malloc(100*sizeof(char));
    memset(hello, 0x00, 100*sizeof(char));

    while(index < 10)
    {
        getchar();
        pid_t chpid = fork();
        if(chpid != 0)
        {
            pids[index++] = chpid;
            continue;
        }

        sprintf(hello, "%d", getpid());

        while(index-- > 0)
        {
            pids[index] = 0;
        }
        if(chpid == 0)
        {
            printf("%04x %d %s %dn", hello, getpid(), hello, strlen(hello));
            sleep(10);
            printf("%04x %d %s %dn", hello, getpid(), hello, strlen(hello));
            break;
        }
    }

    free(hello);
    while(index-- > 0)
    {
        printf("%dn", pids[index]);
    }
    return 0;
}


关于priintf的那两句,有个疑问:
多进程会把动态分配的内存也拷贝一份么?打印出来hello指向的地址是为什么一样的,却可以存放不同的内容?

附上输入:
82de008 20981 20981 5

82de008 20982 20982 5

82de008 20987 20987 5

82de008 20988 20988 5

82de008 20993 20993 5

82de008 20994 20994 5

82de008 20995 20995 5

82de008 21000 21000 5

82de008 21001 21001 5
82de008 20981 20981 5
82de008 20982 20982 5
82de008 20987 20987 5
82de008 20988 20988 5
82de008 20993 20993 5
82de008 20994 20994 5
82de008 20995 20995 5
82de008 21000 21000 5
82de008 21001 21001 5

[ 本帖最后由 onmeiei 于 2009-12-7 19:32 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2009-12-07 19:31 |只看该作者
自己先顶一下

论坛徽章:
0
3 [报告]
发表于 2009-12-07 19:36 |只看该作者
是不是因为指针的地址是相对的地址,不是内存上的绝对地址???

论坛徽章:
4
2015年辞旧岁徽章
日期:2015-03-03 16:54:152015年迎新春徽章
日期:2015-03-04 09:56:11IT运维版块每日发帖之星
日期:2016-08-11 06:20:00IT运维版块每日发帖之星
日期:2016-08-15 06:20:00
4 [报告]
发表于 2009-12-07 21:08 |只看该作者
原帖由 onmeiei 于 2009-12-7 19:36 发表
是不是因为指针的地址是相对的地址,不是内存上的绝对地址???

不是绝对地址(物理地址),而是逻辑地址。也就是程序地址空间中的地址。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP