Linux下进程通信之:有名管道

进程通信:进程与进程间的数据交换,称为进程通信。进程通讯的方式有:共享内存、信号量、管道、消息队列、socket等等。

管道:是一种基于文件的描述符,可以调用read、write和close等操作文件的接口来操作。它是基于文件描述符的通信方式,它是半双工模式。分为有名管道和无名管道。

无名管道:只适用于父子进程之间通信;管道能够把信息从一个进程的地址空间拷贝到另一个进程的地址空间。fd[0]为管道里的读取端,fd[1]则为管道的写入端。管道是一个单向通信信道,如果进程间要进行双向通信,通常需要定义两个管道。

有名管道:有自己的名字和访问权限的限制,就像一个文件一样。它可以用于不相关进程间的通信,进程通过使用管道的名字获得管道。通过系统调用read(), write()函数进行读写操作来实现。

-------------------------write--------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
    int fd;
    char buff[] = "hello,is me!\n";
    remove("temp_fifo");
    if((mkfifo("temp_fifo", O_CREAT|O_RDWR|0777))<0)
    {
        printf("mkfifo is error/n");
        return -1;
    }
    if((fd = open("temp_fifo",O_WRONLY))<0)
    {
        printf("open is error/n");
        return -1;
    }
    if(write(fd,buff,strlen(buff))<0)
    {
        printf("write is error/n");
        return -1;
    }

    close(fd);
    return 0;
}


-------------------------read--------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
    int fd;
    char buff[32] = {0};
 
    if((fd = open("temp_fifo",O_RDONLY))<0)
    {
        printf("open is  error/n");
        return -1;
    }
    if((read(fd,buff,sizeof(buff)))<0)
    {
        printf("write is  error/n");
        return 0;
    }

    printf("buff: %s/n", buff);
    close(fd);
    return 0;
}

fifo_test1.c负责写,fifo_test2.c负责读。结果:

猜你喜欢

转载自blog.csdn.net/weixin_42432281/article/details/87733238