您的位置:首页 > 其它

编写两个进程a和b,利用共享内存技术,a向共享内存写字符串,b将从共享内存中读到的字符串在屏幕上打印出来。

2016-07-09 12:55 435 查看
创建一个共享内存

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: