- 论坛徽章:
- 0
|
功能:
code7-3-b.c 从键盘读入数据,存放在共享内存中。
code7-3-a.c则隔10秒检测一次共享内存, 并从共享内存中读取数据,显示到屏幕上。
代码如下:
//code7-3-a.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define BUF_SIZE 1024
#define MYKEY 24
int main(void)
{
int shmid;
char *shmptr;
if(shmid = shmget(MYKEY, BUF_SIZE, IPC_CREAT) == -1) {
printf("shmget error\n");
exit(1);
}
if ((shmptr = shmat(shmid, 0, 0)) == (void *)-1) {
fprintf(stderr, "shmat error\n");
exit(1);
}
while(1) {
printf("string: %s\n", shmptr);
sleep(10);
}
shmdt(shmptr);
exit(0);
}
//code7-3-b.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define BUF_SIZE 1024
#define MYKEY 24
int main(void)
{
int shmid;
char *shmptr;
if (shmid = shmget(MYKEY, BUF_SIZE, IPC_CREAT) == -1) {
printf("shmget error\n");
exit(1);
}
if ((shmptr = shmat(shmid, 0, 0)) == (void *)-1) {
fprintf(stderr, "shmat error\n");
exit(1);
}
while(1) {
scanf("input string: %s\n", shmptr);
}
shmdt(shmptr);
exit(0);
} |
|