Linux管道(有名管道)

Linux:

是一套免费使用和自由传播的类Unix操作系统,是一个基于POSIX和UNIX的多用户、多任务、支持多线程和多CPU的操作系统。它能运行主要的UNIX工具软件、应用程序和网络协议。它支持32位和64位硬件。Linux继承了Unix以网络为核心的设计思想,是一个性能稳定的多用户网络操作系统。它主要用于基于Intel x86系列CPU的计算机上。这个系统是由全世界各地的成千上万的程序员设计和实现的。其目的是建立不受任何商品化软件的版权制约的、全世界都能自由使用的Unix兼容产品。

一、管道

管道,分为无名管道和有名管道,是 UNIX 系统IPC最古老的形式,是进程间通讯的一种

有名管道特点:
1.有名字,储存于普通文件系统中
2.任何具有相应权限的进程都可以使用open()来获取FIFO的文件描述符
3.跟普通文件一样,用read()和writ()来读和写
4.FIFO文件里面的内容被读取后就消失了,而普通文件的不会

创建有名管道函数和所需头文件

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

int mkfifo(const char* pathname,mode_t mode)

其函数创建有名管道成功则返回0,若失败则返回-1

有名管道就相当于创建了一个有名字的管道,可以让不同的进程使用,这就实现了进程间的通讯
这里的管道就是管道文件,不同的进程通过write和read和open就可以完成通讯

例如:

1.首先创建有名管道

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

int main()
{
    int fd = mkfifo("./myfifo",0777);
    if(fd == -1)
    {
        printf("creat mkfifo fail\n");
        return fd;
    }
    else
    {
        printf("creat mkfifo success\n");
    }
    return 0;
}

2.创建两个不同的进程
(1)first

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

int main()
{
    int fd = open("./myfifo",O_WRONLY);
    if(fd == -1)
    {
        printf("first open myfifo fail\n");
        return fd;
    }
    else
    {
        printf("first open myfifo success\n");
    }

    char w_buff[] = "hello fifo";
    write(fd,w_buff,sizeof(w_buff));

    close(fd);
    return 0;
}

(2)second

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

int main()
{
    int fd = open("./myfifo",O_RDONLY);
    if(fd == -1)
    {
        printf("second open myfifo fail\n");
        return fd;
    }
    else
    {
        printf("second open myfifo success\n");
    }

    char r_buff[128] = {0};
    read(fd,r_buff,127);
    printf("r_buff = %s\n",r_buff);

    close(fd);

    return 0;
}
发布了28 篇原创文章 · 获赞 0 · 访问量 999

猜你喜欢

转载自blog.csdn.net/wfea_lff/article/details/103993574