C语言如何实现一个进程将字符串写入某地址,另一个进程读取该地址获取字符串?
问题描述:
如题,最好提供函数或代码,感谢!
答
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#define POS ((void*)0x7ffff7dff000)
int main()
{
int fd ,ret ,*pos;
if( -1 == (fd = shm_open("/test",O_RDWR|O_CREAT,0777)))
{
return 0;
}
if(-1 == ftruncate(fd,1024))
return 0;
if(MAP_FAILED == (pos = mmap(POS,1024,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_FIXED,fd,0)))
{
return 0;
}
printf("%d\n",*pos);
*pos = 4;
printf("%d\n",*pos);
while(1);
return 0;
}
编译 gcc file.c -lrt
答
server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
char buf[10];
char *ptr;
int main()
{
int fd;
fd = shm_open( "region" , O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd<0) {
printf ( "error open region\n" );
return 0;
}
ftruncate(fd, 90);
char *ptr = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
printf ( "error map\n" );
return 0;
}
ptr = "dcba";
return 0;
}
client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
char buf[10];
char *ptr;
int main()
{
int fd;
fd = shm_open( "region" , O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd<0) {
printf ( "error open region\n" );
return 0;
}
ftruncate(fd, 90);
char* ptr = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
printf ( "error map\n" );
return 0;
}
printf ("ptr : %s\n" , ptr);
return 0;
}
请问我的code问题在哪