进程通信程序整理---管道(Linux)

来源:互联网 发布:mac加速的视频播放器 编辑:程序博客网 时间:2024/05/19 17:10

一、有名管道

#include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(){    pid_t pid;  //定义一个变量,赋值进程创建的返回值    int fd[2]={0};   //定义一个数组,作为管道的两端(读端和写端)    int count = 0;  //用结果直观来看管道通信    int ret;   //返回读写的返回值    pipe(fd);   //创建管道    pid = fork(); //创建进程                    //注意:要在创建进程之前建立管道,这样是建立一个管道,子父进程分别对应读写端。如果写在后面,程序就会分别在子父进程中建立管道,导致通信失败。    if(-1 == pid)   //创建进程失败    {        perror("fork");        exit(1);    }    else if(0 == pid)   //子进程    {        sleep(1);               count++;        printf("child process count:%d\n",count);        ret = write(fd[1],&count,sizeof(count));   //管道写端写入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;}执行结果:child process count:1parent process count :2 

二、无名管道

读文件:#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include<unistd.h>#include<stdio.h>#include<stdlib.h>#include<string.h>int main(){    int ret,fd;       char buf[100]={0};    ret = mkfifo("fifo.tmp",O_CREAT|O_EXCL);   //mkfifo()使用路径名称创建一个FIFO特殊文件,模式指定了FIFO的权限。这个文件类似于一个管道,但是它是以一种不同的方式在一个管道中创建的,而不是作为一个匿名的通信渠道,通过调用mkfifo()将一个FIFO特殊文件输入到文件系统中。一旦您以这种方式创建了FIFO特殊文件,任何进程都可以打开它阅读或写作,就像普通的文件一样。但是,在你对其进行任何输入或输出操作之前它必须同时在两端同时打开。打开一个FIFO的读取通常会阻塞,直到其他进程打开相同的FIFO对于写作,反之亦然。    if(-1 == ret)    {        perror("fifo");        exit(1);    }    fd = open("fifo.tmp",O_RDONLY); //以只读的方式打开    if(-1 == fd)    {        perror("open");        exit(1);    }    while(1)    //制作一个循环用来读取数据    {        ret = read(fd,buf,sizeof(buf)); //将文件中内容读到buf中        if(-1 == ret)        {            perror("read");            exit(1);        }        if(!strncmp(buf,"bye",3)) //读到bye结束(将buf中前三个字符和bye比较,一样则返回0)        {            break;        }        printf("read:%s\n",buf);        memset(buf,0,sizeof(buf)); //将buf中的内容初始化    }    return 0;}写文件:#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include<unistd.h>#include<stdio.h>#include<stdlib.h>#include<string.h>int main(){    int ret,fd;    char buf[100]={0};    fd = open("fifo.tmp",O_WRONLY); //以只写的方式打开文件    if(-1 == fd)    {        perror("open");        exit(1);    }    while(1)    {        scanf("%s",buf);        ret = write(fd,buf,sizeof(buf)); //将buf中内容写到文件中        if(-1 == ret)        {            perror("write");            exit(1);        }        if(!strncmp(buf,"bye",3))        {            break;        }        memset(buf,0,sizeof(buf));    }    unlink("fifo.tmp");//删除文件,否则下次运行该程序会报错,报错类型为该文件已存在    return 0;}执行结果:hello                   read:hellowrold                   read:wroldbye  !
原创粉丝点击