linux共享内存通信问题

hanyunqi hanyunqi 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我想通过共享内存(shmget/shmat/shmdt/shmctl)实现父子进程间的通信(fork())。
主要内容就是,申请一段共享内存,子进程向这段内存中写数据,父进程读出来。
可是,我在子进程中写完了,在子进程中可以读,在父进程中却读不出来。
这个问题,已经困扰我一天了,求大神帮忙。
源代码如下:

#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;
}


运行结果如下:
shm_id = 2261058
This is first time, pid = 0
This is secONd time, pid = 0
This is the child Process.
123qweasd123
This is third time, pid = 0
This is fouth time, pid = 0
shmdt == -1
shmdt error: Invalid argument
This is first time, pid = 13324
This is secONd time, pid = 13324
This is the parent Process.

This is third time, pid = 13324
This is fouth time, pid = 13324
shmdt == -1
shmdt error: Invalid argument
...全文

相关推荐

评论 8
收藏 已收藏
分享
返回顶部
hanyunqi
C++ 语言 65,214 成员 250,514 内容