• 手机版

    扫码体验手机版

  • 微信公众号

    扫码关注公众号

国内首家协议开发

软芯音视解码保护平台

在线
客服

发布
需求

在线
聊天

天盟
APP

天盟APP下载

关注
微信

微信扫一扫访问
顶部

子线程输出语句输出两遍

代码如下,使用了共享内存,但是子线程的代码执行了两次,不明白为什么
#include #include #include #include #include #include #include //#include //#include int main(){    key_t key;    key = ftok("/tmp", 55);    int size = getpagesize();    int shmid = shmget(key, size, IPC_CREAT|00777);    if(shmid < 0)    {        printf("shmget error\n");        return -1;    }    int *p = (int *)shmat(shmid, NULL, 0);    *p = 1;    printf("\nopration *p=1\nthis is father: *p=1=%d\n", *p);    pid_t pid = fork();    if(pid == 0);    {        int *sp = (int *)shmat(shmid, NULL, 0);        *sp = 5;        printf("\nopration *sp=5\nthis is son: *sp=5=%d\n", *sp);        printf("this is son: *p=1=%d\n", *p);    }    wait(NULL);    return 0;}输出结果如下:

opration *p=1this is father: *p=1=1opration *sp=5this is son: *sp=5=5this is son: *p=1=5opration *sp=5this is son: *sp=5=5this is son: *p=1=5

免责声明:本内容仅代表回答会员见解不代表天盟观点,请谨慎对待。

版权声明:作者保留权利,不代表天盟立场。

使用道具 举报

全部参与2

问题就是出在
if(pid==0);多了个分号,去掉分号就正常了,犯了个低级错误

使用道具 举报

子进程创建会复制父进程的所有东西,所以if上面那个输出会输出,把上面那个输出用父进程判断条件(大于0)扩起来,就不会了

使用道具 举报

发新帖

发布任务需求已有1031168位用户正在使用天盟网服务

发布分类: *
任务预算: *
需求内容: *
手机号码: *
任务商家报价为
  • 预算价 :
  • 成交价 :
  • 完工期 :
  • 质保期 :

* 最终任务项目以服务商报价、双方协商为准!