//code7-3-a.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#define BUF_SIZE 1024
int shmid;
char *shmptr;
void ipc_rmid_handler(int s)
{
if(shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl");
exit(1);
}
printf("\n");
shmdt(shmptr);
exit(0);
}
int main(void)
{
key_t key;
key = ftok("/etc/passwd", 0);
if (key == -1) {
perror("ftok");
exit(1);
}
if((shmid = shmget(key, BUF_SIZE,
IPC_CREAT | 0666)) == -1) {
perror("shmget");
exit(1);
}
if ((shmptr = (char *)shmat(shmid,
NULL, 0)) == ((void *)(-1))) {
perror("shmat");
exit(1);
}
while(1) {
signal(SIGINT, ipc_rmid_handler);
signal(SIGQUIT, ipc_rmid_handler);
printf("recvfrom string: %s\n", shmptr);
sleep(10);
}
exit(0);
}
|
//code7-3-b.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#define BUF_SIZE 1024
int shmid;
char *shmptr;
void ipc_rmid_handler(int s)
{
if ((shmctl(shmid, IPC_RMID, NULL)) == -1) {
perror("shmctl");
exit(1);
}
printf("\n");
shmdt(shmptr);
exit(0);
}
int main(void)
{
key_t key;
key = ftok("/etc/passwd", 0);
if (key == -1) {
perror("ftok");
exit(1);
}
if ((shmid = shmget(key, BUF_SIZE,
IPC_CREAT | 0666)) == -1) {
perror("shmget");
printf("shmget error\n");
exit(1);
}
if ((shmptr = (char *)shmat(shmid,
NULL, 0)) == ((void *)(-1))) {
perror("shmat");
fprintf(stderr, "shmat error\n");
exit(1);
}
while(1) {
signal(SIGINT, ipc_rmid_handler);
signal(SIGQUIT, ipc_rmid_handler);
printf("input string: ");
scanf("%s", shmptr);
printf("\n");
}
exit(0);
}
|
功能:通过共享内存实现通信。
程序code7-3-b.c 从键盘读入数据,存放在共享内存中。
$ ./b
input string: hello
程序code7-3-a.c刚每隔10秒检测一次共享内存,并从共享内存中读取数据,显示到屏幕上。
$./a
recvfrom string: hello
阅读(463) | 评论(0) | 转发(0) |