64,637
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <malloc.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char* argv[])
{
int shm_id, shm_key = 12345;
unsigned short errno;
void **shmptr;
shm_id = shmget((key_t)shm_key, (size_t)(sizeof(char) * 100), IPC_CREAT|0666);
if (shm_id < 0)
{
printf("change the shm_key\n.");
return 0;
}
printf("shm_id = %d\n", shm_id);
shmptr = new void *;
*shmptr = NULL;
pid_t pid;
int count=0;
pid = fork();
printf( "This is first time, pid = %d\n", pid );
printf( "This is secONd time, pid = %d\n", pid );
if ( pid>0 )
{
*shmptr = (char *)shmat(shm_id, 0, 0);
if (*shmptr == (void *)-1)
{
printf("shmat fail.\n");
perror("shmat error");
return 0;
}
//sleep(1);
printf( "This is the parent Process.\n");
printf("%s\n",shmptr);
}
else if ( 0 == pid )
{
*shmptr = (char *)shmat(shm_id, 0, 0);
if (*shmptr == (void *)-1)
{
printf("shmat fail.\n");
perror("shmat error");
return 0;
}
printf( "This is the child Process.\n");
strcpy((char *)shmptr, "123qweasd123");
printf("%s\n",shmptr);
}
else
{
printf( "fork failed.\n" );
}
printf( "This is third time, pid = %d\n", pid );
printf( "This is fouth time, pid = %d\n", pid );
//printf("%s\n",shmptr);
//释放共享内存
if (-1 == shmdt(shmptr))
{
printf("shmdt == -1\n");
perror("shmdt error");
return 0;
}
if (-1 == shmctl(shm_id, IPC_RMID, 0))
{
printf("shmctl == -1\n");
return 0;
}
return 0;
}