linux两个程序通过共享内存通信的一个简单例子

本文介绍了一个简单的共享内存程序实现,包括服务器端将数据写入共享内存区及客户端从共享内存读取并显示数据的过程。该程序使用C++编写,通过shmget、shmat等系统调用实现共享内存段的创建、连接和数据交互。

写共享内存程序:

 

/* * File: server.cpp * Author: centos *说明:从键盘读入数据,存放在共享内存中。 * Created on 2010年3月1日, 下午3:44 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #define BUF_SIZE 1024 #define MYKEY 114 int main(int argc, char** argv) { int shmid; char *shmptr; struct shmid_ds shmbuf; system("ipcrm -M114"); //调试程序时用 shmid = shmget(MYKEY, BUF_SIZE, (IPC_CREAT |0777) ); if ( -1 == shmid ) { printf("server shmget error!/n"); fprintf(stderr, "Error: %d - %s/n", errno, strerror(errno)); exit(1); } shmptr = (char *) (shmat(shmid, 0, 0)) ; if ( -1 == (int) shmptr ) { printf("server shmat error!/n"); fprintf(stderr, "Error: %d - %s/n", errno, strerror(errno)); if(shmctl(shmid,IPC_RMID,&shmbuf) < 0) { perror("shmctl error"); fprintf(stderr, "Error: %d - %s/n", errno, strerror(errno)); } exit(1); } strcpy(shmptr,"this is a test. /n"); while(1) { printf("Please input:"); scanf("%s",shmptr) ; while ('/n' != getchar() ); // fflush(stdin); // printf("your input: %s/n", shmptr); if (! strcmp(shmptr,"quit")) break; } shmdt(shmptr); if(shmctl(shmid,IPC_RMID,&shmbuf) < 0) perror("shmctl error"); return (EXIT_SUCCESS); }

 

 

 

 

 

 

 

读共享内存的程序:

/*
 * File:   main.cpp
 * Author: centos
 *
说明:从共享内存中读取数据,显示到屏幕上。
 * Created on 2010年3月2日, 上午10:47
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <errno.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define BUF_SIZE 1024
#define MYKEY 114

/*
 *
 */
int main(int argc, char** argv)
{
    int shmid;
    char *shmptr;
    struct shmid_ds shmbuf;
    char last_str[1024];

    if ( ( shmid = shmget(MYKEY, BUF_SIZE, IPC_CREAT) ) == -1 )
    {
        printf("clinet shmget error!/n");
        exit(1);
    }
    
    shmptr = (char *) shmat(shmid, 0, 0);
    if ( -1 == (int) shmptr )
    {
        printf("clinet shmat error!/n");
        fprintf(stderr, "Error: %d - %s/n", errno, strerror(errno));
        exit(1);
    }

    while(1)
    {
        
//        if((strlen(last_str) != strlen(shmptr)) ||
        if( ( 0 != strcmp(last_str,shmptr)))
        {
            printf("%s  %s/n", last_str,shmptr);
            strcpy(last_str,shmptr);
        }
        if (! strcmp(shmptr,"quit")) break;        
    }
    shmdt(shmptr);
    if(shmctl(shmid,IPC_RMID,&shmbuf) < 0) perror("Close 共享内存出错shmctl error");
    return (EXIT_SUCCESS);
}

转载于:https://www.cnblogs.com/johnphan/archive/2010/03/02/9191272.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值