为了账号安全,请及时绑定邮箱和手机立即绑定

子线程输出语句输出两遍

子线程输出语句输出两遍

C C++
你想象不到我有多执着 2017-04-13 09:31:15
代码如下,使用了共享内存,但是子线程的代码执行了两次,不明白为什么#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/wait.h> #include <stdlib.h> //#include <sys/signal.h> //#include <stdlib.h> 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=1 this is father: *p=1=1 opration *sp=5 this is son: *sp=5=5 this is son: *p=1=5 opration *sp=5 this is son: *sp=5=5 this is son: *p=1=5
查看完整描述

2 回答

?
你想象不到我有多执着

TA贡献1条经验 获得超0个赞

问题就是出在

if(pid == 0);

多了个分号,去掉分号就正常了,犯了个低级错误

查看完整回答
反对 回复 2017-10-18
?
遥不可及不放弃

TA贡献15条经验 获得超5个赞

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

查看完整回答
反对 回复 2017-08-16
  • 你想象不到我有多执着
    你想象不到我有多执着
    可能是我没有表达清楚,我现在才发现问题出在哪了,问题出在if(pid == 0);多了个分号,不过也很感谢你的回答
  • 2 回答
  • 0 关注
  • 1544 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信