请教一个共享内存问题

发表于:2007-05-26来源:作者:点击数: 标签:
代码: #include stdio.h#include sys/types.h#include errno.h#include sys/shm.h#include sys/ipc.h#include string.h#include sys/sem.h#include unistd.h#define K 1024#define SHMSIZE K*4*16#define SHMFLAGS IPC_CREAT|0644struct mystruct{ int user_
 
代码:

#include "stdio.h" #include "sys/types.h" #include "errno.h" #include "sys/shm.h" #include "sys/ipc.h" #include "string.h" #include "sys/sem.h" #include "unistd.h" #define K 1024 #define SHMSIZE K*4*16 #define SHMFLAGS IPC_CREAT|0644 struct mystruct{ int user_name; struct mystruct * next; }; typedef struct mystruct * MYSTRUCT; int shmid; cleanup(){ shmctl(shmid,IPC_RMID,0); exit(0); } main(){ char * addr1; int i; pid_t pid; MYSTRUCT user_struct; MYSTRUCT p,q,r; for(i=0;i<20;i++) signal(i,cleanup); shmid = shmget(IPC_PRIVATE,SHMSIZE,SHMFLAGS); if(shmid == -1){ printf("shm create failed!\n"); }else{ printf("shared memory segment ID = %d\n",shmid); addr1 = shmat(shmid,0,0); if((pid=fork())==0){ user_struct = (MYSTRUCT)addr1; r = user_struct; i=0; while(i<100){ /* q=(MYSTRUCT)malloc(sizeof(struct mystruct)); */ q=user_struct++; q->user_name = i; q->next=NULL; r->next=q; r=r->next; i++; /* sleep(1); */ /* 此处如果不加sleep(1),则一切正常,如果加上sleep(1), 那么仅仅打印链表的第一二个节点的地址,等很久以后, 可能会打印以后节点的地址,是不是由于进程不同步的问题? */ } } if((pid=fork())==0){ while(1){ p= (MYSTRUCT)addr1; i=0; while(p!=NULL){ printf("0x%x\n",p); p=p->next;

i++;
      }
      sleep(2);
   }
   }
   shmdt(addr1);

   shmctl(shmid,IPC_RMID,0);
  }   

} 

 fork()两次做什么,是不是写错了?

原文转自:http://www.ltesting.net

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)