Linux进程间同步和通信2:命名管道

2018-06-20  本文已影响0人  AmberXiao

目录:
1. 半双工管道
2. 命名管道
3. 消息队列
4. 信号量
5. 信号
6. 共享内存


2 命名管道(FIFO,first in first out)

2.1 特点

2.2 mkfifo()函数

#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(
   const char *pathname,
  mode_t mode
 );

2.3 mkfifo()例程

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

int main()
{
    char buf[80];
    int fd;
    pid_t pid;
    int ret;

    unlink("./my_fifo");//删除文件
    mkfifo("./my_fifo",0777);

    pid=fork();
    if(pid==-1)
    {
        printf("fork error\n");
        return -1;
    }
    if(pid==0)
    {
        char s[]="hello\n";
        fd=open("./my_fifo",O_RDONLY);
        ret=write(fd, s, sizeof(s));
        printf("child has write %d to fifo\n",ret);
        close(fd);
    }
    else
    {
        fd=open("./my_fifo",O_RDONLY);
        read(fd,buf, sizeof(buf));
        printf("read from fifo:%s\n",buf);
        close(fd);
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读