我是 IPCS 概念的新手,我想实现一个进程创建并初始化共享内存,然后调用另一个进程,该进程附加到同一共享内存段并打印共享内存中的数据。但是我无法实现它:
AlgoCommon.h
struct sub_algo_shm
{
int time;
int pno;
};
struct AlgoShm
{
int head;
int tail;
char fFlag;
struct sub_algo_shm algoshm;
};
算法油门.c
#define key (key_t)111119
#define SHM_SIZE 1024
int main()
{
int shmid ;
struct timeval CurTime;
struct timespec nTime;
struct AlgoShm *shmaddr,*ptr;
ptr = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));
//Creating Shared Memory
if((shmid = shmget(key,SHM_SIZE,0644 |IPC_CREAT)) < 0)
{
perror("shmget:error");
}
else
{
printf("Shm created key=[%d] \n Segment Id [%d] ",key,shmid);
//Attaching to Shared Memory
shmaddr = (struct AlgoShm *)shmat(shmid,0,0);
if(shmaddr < 0)
{
perror(" shmat :error");
}
else
{
printf(" SHM Segment attached at [%x] ",shmaddr);
}
//Loading/Initializing Data Blocks in SHM
clock_gettime(CLOCK_REALTIME,&nTime);
printf(" Time in N secs[%ld] \n ",nTime.tv_nsec);
ptr->head = 5;
ptr->tail = 3;
ptr->fFlag = '0';
ptr->algoshm.time = 0;
ptr->algoshm.pno = 1;
//memcpy(shmaddr,&ptr,sizeof(ptr));
printf(" AlgoThrottle|ptr->head [%d] ",ptr->head);
// sleep(1);
system("./AlgoRead");
}
return 0;
}
算法阅读.c
#define key (key_t)111119
#define SHM_SIZE 1024
int main()
{
int shmid ;
struct AlgoShm *shmaddr,*ptr1 ;
ptr1 = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));
if((shmid = shmget(key,SHM_SIZE,0)) < 0)
{
perror(" AlgoRead|shmget:error ");
}
else
{
printf(" AlgoRead|SHM Created shmid [%d] ",shmid);
if((shmaddr = (struct AlgoShm *)shmat(shmid,0,0)) < 0)
{
perror("AlgoRead|shmat error");
}
else
{
//memcpy(ptr1,shmaddr,sizeof(struct AlgoShm));
printf(" AlgoRead|Attached to Segment at Address[%x] \n ",shmaddr);
printf(" AlgoRead|ptr1->head [%d] ptr1->tail [%d] ptr1->fFlag[%c] \n ",ptr1->head,ptr1->tail,ptr1->fFlag);
}
}
return 0;
}
这是我的输出:
Shm created key=[111119]
Segment Id [1179615678] SHM Segment attached at [4a6b4000] Time in N secs[114594083]
AlgoRead|SHM Created shmid [1179615678] AlgoRead|Attached to Segment at Address[624cb000]
AlgoRead|ptr1->head [36810768] ptr1->tail [0] ptr1->fFlag[▒]
AlgoThrottle|ptr->head [5]
此外,系统调用的输出首先显示,然后是 printf 语句,即使在我在调用 system() 之前使用了 sleep(1) 之后