创建一个共享内存
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(int arg, char *args[])
{
int shmid = shmget(IPC_PRIVATE, 1024, 0666);
if (shmid < 0)
{
printf("error\n");
} else
{
printf("succes\n");
}
shmat(shmid, NULL, )
return EXIT_SUCCESS;
}然后使用这个共享内存
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/shm.h>
int main(int arg, char *args[])
{
char *shmbuf;
int shmid = 0;
if (arg > 2)
{
shmid = atoi(args[1]);
shmbuf = shmat(shmid, 0, 0);
if (atoi(args[2]) == 1)
{
scanf("%s", shmbuf);
}
if (atoi(args[2]) == 2)
{
printf("%s\n", shmbuf);
}
shmdt(shmbuf);
}
return 0;
}
本文介绍了一个简单的共享内存程序实现过程,包括如何创建共享内存段及如何在不同进程中使用该内存段进行数据交换。通过示例代码展示了从创建共享内存到读写数据的具体步骤。
368

被折叠的 条评论
为什么被折叠?



