Chinaunix首页 | 论坛 | 博客
  • 博客访问: 160466
  • 博文数量: 83
  • 博客积分: 3956
  • 博客等级: 中校
  • 技术积分: 663
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-24 16:29
文章分类

全部博文(83)

文章存档

2010年(83)

我的朋友

分类: C/C++

2010-10-15 19:46:37

//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) |
给主人留下些什么吧!~~