Linux下共享内存及线程的创建

共享内存的创建
接口的.h文件


#ifndef _COMM_H
#define _COMM_H

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


#define PATHNAME "."
#define PROJ_ID  06666

static int Comm(int size,int flag);
int Creat(int size);//创建
int Get();//获取
int Destory(int shimd);//销毁
char* Shmat(int shmid);//共享内存的挂接
int Shmdt(const char* addr);//删除链接

#endif

.c文件

#include"comm.h"

static int Comm(int size,int flag)
{
    key_t key = ftok(PATHNAME,PROJ_ID);
    int shmid = shmget(key,size,flag);
    if(shmid < 0 )
    {
        perror("shmget");
        return -1;
    }
    return shmid;
}
int Creat(int size)//创建
{
    return Comm(size,IPC_CREAT|IPC_EXCL|0x666);
}
int Get()//获取
{
    return Comm(0,IPC_EXCL);
}
int Destory(int shmid)//销毁
{
    if(shmctl(shmid,IPC_RMID,NULL)<0)
    {
        perror("shmctl");
        return -1;
    }
    return 0;
}
char* Shmat(int shmid)//共享内存的挂接
{
    char* ret = shmat(shmid,NULL,0);
    if(ret == (char*)-1)
    {
        perror("shmat");
        return NULL;
    }
    return ret;
}
int Shmdt(const char* addr)
{
    if(shmdt(addr) < 0)
    {
        perror("shmdt");
        return -1;
    }
    return 0;
}

测试用例
server.c文件

#include"comm.h"

int main()
{
    int shimd = Creat(4096);
    char* buf = Shmat(shimd);
    int i = 0;
    while(i < 4096)
    {
        buf[i] = 'a' + i%26;
        buf[i+1] = '\0';
        i++;
    sleep(2);
    }
    Destory(shimd);
    return 0;
}

client.c

#include"comm.h"

int main()
{
    int shmid = Get();
    char* buf = Shmat(shmid);
    int i = 0;
    while(i < 4096)
    {
        printf("%s\n",buf);
        i++;
    sleep(2);
    }
    return 0;
}

线程的创建
.c文件

#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>

void thread()
{
    while(1)
    {
        printf("new thread tid = %lu pid = %d\n",pthread_self(),getpid());
        sleep(1);
    }
}

int main()
{
    pthread_t id;
    int ret = pthread_create(&id,NULL,(void*)thread,NULL);
    if(ret != 0)
    {
        printf("Creat error!\n");
        return -1;
    }
    while(1)
    {
        printf("man thread tid = %lu pid = %d\n",pthread_self(),getpid());
        sleep(1);
    }
    return 0;
}

Makefile文件

mypthread:mypthread.c
    gcc -o $@ $^ -lpthread

.PHONY:clean
clean:
    rm -f mypthrea

结果截图
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值