文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>进程间通信示例 <共享内存>

进程间通信示例 <共享内存>

时间:2010-10-15  来源:aaron_xueli

//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

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载