[Linux]进程通信(IPC)

本文详细介绍了Linux下的进程通信方式,包括管道(PIPE)、命名管道(FIFO)、信号(Signal)、消息队列(Message Queues)和共享内存等。通过函数调用和源码分析,阐述了各种通信方式的使用方法及其特点,如管道的半双工特性、命名管道的文件系统存在性以及消息队列的数据结构要求等。
摘要由CSDN通过智能技术生成

一、管道(PIPE)

1.1 函数

  • int pipe(int file_descriptor[2]); //建立管道,该函数在数组上填上两个新的文件描述符后返回0,失败返回-1。  

        file_descriptor[0]用于读出数据,读取时必须关闭写入端,即close(file_descriptor[1]);
        file_descriptor[1]用于写入数据,写入时必须关闭读取端,即close(file_descriptor[0]);

    只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程).比如fork或exec创建的新进程.

    管道是半双工的,数据只能向一个方向流动;需要双方通信时,需要建立起两个管道.

  • ssize_t read(int fd, void * buf, size_t count); //读数据file_descriptor[0]
  • ssize_t write (int fd, const void * buf, size_t count); //写数据file_descriptor[1]

1.2 源码

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

#include <fcntl.h>
#include <errno.h>

#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>

typedef struct _IPC_MESSAGE{
    int len;
    char *body;
}IPC_MSG;

int ipc_read(int fd){
    IPC_MSG rMsg;

    read(fd,&rMsg.len,sizeof(int));
    printf("[read]msg len:%d\n",rMsg.len);

    int lenBody = rMsg.len - sizeof(int);
    rMsg.body = (char*)malloc(lenBody);
    //printf("[read]body len:%d\n",lenBody);
    int ret = read(fd,(void*)rMsg.body,lenBody);
    //printf("[read]body ret:%d\n",ret);
    rMsg.body[lenBody] = '\0';
    printf("[read]msg body:%s\n",rMsg.body);

    return 0;
}

int ipc_write(int fd,char* buffer){
     printf("[write]msg body:%s\n",buffer);

     IPC_MSG wMsg;
     wMsg.body = buffer;
     wMsg.len = sizeof(int) + (strlen(wMsg.body)+1);
     printf("[write]msg len:%d\n",wMsg.len);

     write(fd,(void*)&wMsg.len,sizeof(int));
     write(fd,(void*)wMsg.body,strlen(wMsg.body)+1);
}

int test_ipc_pipe(){
    printf("Test for pipe\n
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值