进程间通信

进程的读写

写文件的进程只能单个运行(写的时候禁止读),读文件的进程可以同时有多个,
读写的互斥锁wsem,rsem
读写进程的优先性同级,读进程有优先权时(读的时候拿走写锁),

进程间通信方式

Pipe, fifo, shared memory, mmap, samaphone, socket, mesgq,
有名管道和无名管道
共享文件
共享内存
消息队列
内存映射
socket监听套接字
信号量

管道

管道通信详解
管道为单向, Pipe,上级进程创建,无名管道通信
pipe, pipe2 - create pipe

   #include <unistd.h>
   int pipe(int pipefd[2]);
   #define _GNU_SOURCE             /* See feature_test_macros(7) */
   #include <fcntl.h>              /* Obtain O_* constant definitions */
   #include <unistd.h>
   int pipe2(int pipefd[2], int flags);
  return -1 为失败

管道通信函数例

// ./named-pipe-chat  发送消息
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

// 用户名的最大长度
#define USER_NAME_MAX_LEN 100
// 发送消息文本的最大长度
#define MSG_MAX_LEN 500
// 文件名的最大长度
#define FILE_NAME_MAX_LEN 100

// 聊天消息结构体类型
struct msg_node 
{
    // 发送消息用户名
    char src_username[USER_NAME_MAX_LEN];
    // 接收消息用户名
    char dst_username[USER_NAME_MAX_LEN];
    // 消息文本
    char text[MSG_MAX_LEN];
};

int main(int argc, char *argv[])
{
    // 判断命令行参数是否满足条件
    if(argc != 2)
    {
        printf("usage : %s <username>\n", argv[0]);
        return 1;
    }

    // 子进程ID
    pid_t child_pid;
    // 登陆用户的命令管道文件名
    char filename[FILE_NAME_MAX_LEN] = {'\0'};

    // 构造登陆用命名的管道文件名,并判定用户是否存在
    sprintf(filename, "%s.fifo", argv[1]);
    if(access(filename, F_OK) != 0)//判断用户名文件是否存在,存在返回0
    {
        mkfifo(filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    }

    // 创建子进程
    if((child_pid = fork()) == 0)       // 子进程中执行的代码,子进程负责接收其他用户发送的消息并打印显示
    {
        int n = 0;
        struct msg_node msg;
        int fd = 0;
        
        // 1.打开登陆用户的管道文件,用于接收其他用户发送的消息数据结构体
        if((fd = open(filename, O_RDONLY)) == -1)
        {
            perror("open failed");
            return 1;
        }
        // 2.循环的从管道文件中读入消息信息,并打印显示
        while( (n = read(fd, &msg, sizeof(msg)) ) > 0)
        {
            printf( "%s ----> %s : %s\n",
            msg.src_username, msg.dst_username, msg.text);
        }
        close(fd);
    }
    else  if(child_pid > 0)          // 父进程,负责从键盘读入相关数据,写入执行用户的管道文件
    {
        struct msg_node msg ;
        int fd = 0;
        // 接收用户的管道文件名
        char dst_filename[FILE_NAME_MAX_LEN] = {'\0'};
                   
        // 发送者永远为当前登录用户
        strcpy(msg.src_username, argv[1]);
        
            // 1.输入接收消息的用户名名称
            printf("to>");
            fgets(&msg.dst_username, USER_NAME_MAX_LEN, stdin);
            // 1.1将用户名末尾的'\n'替换为'\0'
            msg.dst_username[strlen(msg.dst_username)-1] = '\0';
            // 1.2构造接收用户的管道文件名
            sprintf(dst_filename, "%s.fifo", msg.dst_username) ;
            // 1.3打开管道文件
            if((fd = open(dst_filename, O_WRONLY)) == -1)
            {
                perror("open failed");
                return 1;
            } 
      // 循环的发送从键盘读入的数据
        while(1)
        {
            // 2.输入待发送的消息字符串
            printf("text>");
            fgets(&msg.text, MSG_MAX_LEN, stdin);
            // 2.2将消息文本末尾的'\n'替换为'\0'
            msg.text[strlen(msg.text)-1] = '\0';
            
            // 3.将构造的消息结构体写入管道文件
                
                
            // 3.2将构造的结构体写入管道文件
            write(fd, &msg, sizeof(msg));
            // 3.3close
        }
       close(fd);
    }
    else
    {
    }
    
    // 删除登陆用户的管道文件
    remove(filename);

    return 0;
}

有名管道通信

mkfifo
mkfifo - make a FIFO special file (a named pipe)
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
return 成功返回0,失败返回1

有名管道--写信息
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int n = 0;
    char buf[1024] = {'\0'};
    int fd = 0;

    // 判断有名管道文件是否存在,不存在则创建
    if(access("test_file.fifo", F_OK) != 0 )
    {
        mkfifo("test_file.fifo", 
            S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    }
    // 1.打开管道文件
    if((fd = open("test_file.fifo", O_WRONLY)) == -1)
    {
        perror("open failed");
        return 1;
    }

    printf("waiting for input data...\n");
    while(1)
    {
        // 2.从标准输入文件中读入数据
        n = read(STDIN_FILENO, buf, 1024);
        // 3.将读到的数据写入到管道文件中
        write(fd, buf, n);
    }
    
    printf("writer process exit...\n");
    
    return 0;
}
有名管道--读取信息
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
    int n = 0;
    char buf[1024] = {'\0'};
    int fd = 0;
    
       
    // 1.打开管道文件
    fd = open("test_file.fifo", O_RDONLY);
    if(fd == -1)
    {
        perror("open failed");
        return 1;
    }
    
    printf("reading for writer data...\n");
    // 2.从管道文件中读取数据
    while((n = read(fd, buf, 1024)) > 0)
    {
        // 3.将读到的数据写入到标准输出文件中
        write(STDOUT_FILENO, buf, n);
    }
    
    printf("reader process exit...\n");
    
    return 0;
} 
互斥锁,线程间通信的函数例
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
//有限资源的使用中,避免死锁。
//哲学家吃饭问题,有五只筷子,五个人,每人用二只,不允许冲突。

#define N 5
sem_t kuaizis[N];
sem_t room;

void *phi_thread_func(void *arg);

int main ()
{
    int i =0;
    pthread_t thread_ids[N];
    sem_init(&room,0,4);
    for(i=0;i<N;i++)
    {
        sem_init(&kuaizis[i],0,1);
    }
    for(i=0;i<N;i++)
    {
        pthread_create(&thread_ids[i],NULL,phi_thread_func,(void **)i);
    }
    for(i=0;i<N;i++)
    {
        pthread_join(thread_ids[i],NULL);
    }
    return 0;
}

void *phi_thread_func(void *arg)
{
int thread_no = (int )arg;
sem_wait(&room);
sem_wait (&kuaizis[thread_no]);
sem_wait(&kuaizis[(thread_no+1)%N]);

printf("%d eating\n",thread_no);

sem_post(&kuaizis[(thread_no+1)%N]);
sem_post(&kuaizis[thread_no]);
sem_post(&room);

pthread_exit(NULL);
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,393评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,790评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,391评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,703评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,613评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,003评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,507评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,158评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,300评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,256评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,274评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,984评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,569评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,662评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,899评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,268评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,840评论 2 339

推荐阅读更多精彩内容