您的位置:首页 > 运维架构 > Linux

Linux进程通信方法--管道

2010-07-28 16:30 501 查看
1 pipe

#include <unistd.h>

int pipe(int filedes[2]);

只能用以父子进程之间进行通信。注意,pfd[0]只能read,pfd[1]只能write.是一个单向的。

2 fifo 即命名管道

#include <sys/stat.h>

int mkfifo(const char *pathname, mode_t mode);

mkfifo() 用法和creat用法相同,创建出一个虚拟的文件,可以在没有关系的进程之间进行共享,传递信息。创建好之后就可以像对待一个文件一样使用它。

注意在非阻塞模式下,write only的打开会直到有read only的open发生时,才会返回。反之read only的open直到write only的open发生时才会返回。在阻塞模式下,read only的open会立刻返回,但是write only的open,在没有为读而打开的情况下会返回1,errno会被置为ENXIO。

示例:

//先执行的进程

#include <sys/stat.h>

#include <stdio.h>

#include <fcntl.h>

#include <errno.h>

int main()

{

    int fd = 0;

    if(mkfifo("fifo.tmp",S_IRUSR | S_IWUSR) < 0)

        perror("mkfifo failed!");

    if((fd = open("fifo.tmp",O_WRONLY)) <= 0 )  

        perror("error open fifo");

    if(write(fd,"hello",6) != 6)

        perror("error write");

    close(fd);

    return 0;

}

//后执行的进程

#include <sys/stat.h>

#include <stdio.h>

#include <fcntl.h>

#include <errno.h>

int main()

{

    int fd = 0;

    char buf[32];

    if((fd = open("fifo.tmp",O_RDONLY)) <= 0 )  

        perror("error open fifo");

    if(read(fd,buf,sizeof(buf)) <= 0)

        perror("error read");

    printf("read %s/n",buf);

    close(fd);

    return 0;

}

第一个程序先运行会阻塞,直到第二个程序运行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux