管道通信

来源:互联网 发布:qq刷人气软件 编辑:程序博客网 时间:2024/05/16 20:29
1.管道通信的特点:
(1)管道是半双工的,先进先出的,它把一个进程的输出和另一个进程的输入连接在一起
(2)一个进程(写进程)在管道的尾部写入数据,另一个进程(读进程)从管道的头部读出数据
2.无名管道和有名管道分别适用的进程是什么?
无名管道用于有血缘关系进程之间的通信;有名管道用于运行同一个系统中的任意两个进程间的通信
3.管道
Pipe
原型:int pipe(int filedes[2])
参数:新建的两个描述符由filedes数组返回。filedes[0]表示管道的读取端,filedes[1]表示管道的写入端
返回值:成功:0;出错:-1
#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <unistd.h>#include <sys/wait.h>int main(){    int ret;    int count=0;    pid_t pid;    int fd[2]={0};    ret=pipe(fd);//before make pid     if(-1==ret)    {        perror("pipe");        exit(1);    }    pid=fork();    if(-1==pid)    {        perror("fork");        exit(1);    }    else if(0==pid)    {        count++;        printf("Child Process :count=%d\n",count);        ret=write(fd[1],&count,sizeof(count));        if(-1==ret)        {            perror("write");            exit(1);        }    }    else    {        ret=read(fd[0],&count,sizeof(count));        if(-1==ret)        {            perror("read");            exit(1);        }        count++;        printf("Parent Process:count=%d\n",count);        waitpid(pid,NULL,0);    }    return 0;}



4.有名管道
mkfifo
原型:int mkfifo(const char *filename,mode_t mode)
函数的参数:filename:有名管道的路径,名称。Mode:管道的方式
O_NONBLOCK:FIFO打开的时候会立刻返回,非阻塞

返回值:成功:0;出错:-1


写入

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int main(){    int fd;    int ret;    char buf[100]={0};    fd=open("2.txt",O_WRONLY);    if(-1==fd)    {        perror("open");        exit(1);    }    while(1)    {        scanf("%s",buf);        ret=write(fd,buf,strlen(buf));        if(-1==ret)        {            perror("write");            exit(1);        }        if(!strncmp(buf,"bye",3))        {            break;        }        memset(buf,0,sizeof(buf));    }    return 0;}


读取

#include <stdio.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <fcntl.h>#include <stdlib.h>int main(){    int ret,fd;    char buf[100]={0};    ret=mkfifo("2.txt",O_CREAT|O_EXCL);    if(-1==ret)    {        perror("mkfifo");        exit(1);    }    fd=open("2.txt",O_RDONLY);    if(-1==fd)    {        perror("open");        exit(1);    }    while(1)    {        ret=read(fd,buf,sizeof(buf));        if(-1==ret)        {            perror("read");            exit(1);        }        if(!strncmp(buf,"bye",3))        {            break;        }        printf("Read from Fifo:%s\n",buf);        memset(buf,0,sizeof(buf));    }    unlink("2.txt");    return 0;}





原创粉丝点击