linux进程通信
作者:mmseoamin日期:2023-12-14


匿名管道

struct_file的两套资源

管道只能单向通信

特征

1.如果管道没有数据 读端在读 默认会直接阻塞正在读取的进程

2.写端写满 在写会阻塞 等待对方读取

管道设计

命名管道

实现管道通信

#pragma once
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define NAME_PIPE "/home/ls/lesson24/tmp2"
bool createFifo(const string& path){
    int n=mkfifo(path.c_str(),0777);
    if(n==0)
        return true;
    else{
        cout<<"errno:"<0){
            buffer[s]=0;
            cout<<"client->server#"< 

共享内存

原理

接口的认识

共享内存的优缺点

和管道对比拷贝次数

实现通信

//comm.hpp
#pragma once
#include
#include
#include
#include
#include
#include
#define PATHNAME "."
#define PROJ_ID 0x66
#define MAX_SIZE 4096
key_t getkey(){
    key_t k=ftok(PATHNAME,PROJ_ID);
    if(k<0){
        std::cerr< 
 
//shm_client.cpp
#include
#include"comm.hpp"
int main(){
    key_t k=getkey();
    printf("key:0x%x\n",k);
    int shmid=getShm(k);
    printf("shmid:%d\n",shmid);
    sleep(5);
    char* start=(char*)attachShm(shmid);  //关联共享内存
    printf("attch sucess,address start:%p\n",start);
    const char* message="hello server,我是另一个进程 正在和你通信";
    pid_t id=getpid();
    int cnt=1;
    while(true){
        sleep(1);
        snprintf(start,MAX_SIZE,"%s[pid:%d][消息编号:%d]",message,id,cnt++);
    }
    detachShm(start);  //去关联
    sleep(5);
    return 0;
}
//shm_server.cpp
#include
#include"comm.hpp"
int main(){
    key_t k=getkey();
    printf("key:0x%x\n",k);
    int shmid=createShm(k);
    printf("shmid:%d\n",shmid);
    sleep(5);
    //关联共享内存
    char *start=(char*)attachShm(shmid);
    printf("attch sucess,address start:%p\n",start);
    //使用
    while(true){
        printf("client say:%s\n",start);
        sleep(1);
    }
    //去关联
    detachShm(start);
    sleep(10);
    //删除共享内存
    delShm(shmid);
    return 0;
}

消息队列(了解)

信号量

为什么要有信号量

信号

实现kill

#include
#include
#include
#include
#include
#include
static void Usage(const std::string &proc){
    std::cout<<"Usage:"< 
 

产生信号的方式

除0的理解

软件条件

#include
#include
#include
#include
#include
#include
#include
/* static void Usage(const std::string &proc){
    std::cout<<"Usage:"< 

闹钟管理

核心转储

阻塞信号

信号捕捉流程

状态切换

实验

#include
#include
#include
#include
#define MAX_SIGNUM 31
#define BLOCK_SIGNAL 2
static std::vector sigarr={2,3};
static void show_pending(const sigset_t &pending){
    for(int signo=MAX_SIGNUM;signo>0;signo--){
        if(sigismember(&pending,signo)){
            std::cout<<"1";
        }
        else
            std::cout<<"0";
    }
    std::cout<<"\n";
}
static void myhandler(int signo){
    std::cout< 
 
 
 

上一篇:2.面向对象编程风格

下一篇:14-1、IO流