您的位置:首页 > 其它

程序:进程间通信——无名管道实例

2017-03-19 00:12 274 查看


无名管道由pipe()函数创建:

                int pipe(int filedis[2]);

    当一个管道建立时,它会创建两个文件描述符:

filedis[0] 用于读管道, filedis[1] 用于写管道(不固定,也可倒过来)

通常先创建一个管道,再通过fork函数创建一个子进程,该子进程会继承父进程所创建的管道

必须在系统调用fork( )前调用pipe( ),否则子进程将不会继承文件描述符

以下程序为父进程传递字母给子进程,子进程将其转化为大写再传给父进程

#include<stdio.h>

#include<ctype.h>

#include<wait.h>

#include<string.h>

#include<errno.h>

#include<unistd.h>

#include<stdlib.h>

int main()

{

    int fd1[2];                         //创建管道文件描述符

    int pid;

  char str[20];                          

  if (pipe(fd1) < 0)           //创建管道

  {

      printf("create pipe error");

    exit(-1);

  }

    int fd2[2];

  if (pipe(fd2) < 0)

  {

      printf("create pipe error");

    exit(-1);

  }

   

  if ((pid = fork()) <0)              //创建子进程, 用fork创建,vfork创建的子进程运行结束再执行父进程

  {

      printf("create pid error");

  }

  else if (pid == 0)          //pid=0 为子进程

  {

      close(fd1[1]);            //关闭第一个通道的写端和第二通道的读端

    close(fd2[0]);

      sleep(2);

    read(fd1[0],str,5);              //从第一个通道读取内容

    for (int i = 0; i < 5; i++)

    {

        if (str[i] > 'a' && str[i] < 'z')

      {

           str[i] = toupper(str[i]);          将读取的内容转化为大写

      }

    }

    write(fd2[1],str,5);                //再写进通道二

      close(fd1[0]);      //将两个通道关闭

    close(fd2[1]);

    exit(0);

  }

  else

  {

      close(fd1[0]);         //在父进程关闭第一通道的读端和第二通道的写端

    close(fd2[1]);

    write(fd1[1],"hello",5);    //在第一通道写

    read(fd2[0],str,5);      //在第二通道读

    printf("%s",str);

    waitpid(pid,NULL,0);  //等到子进程结束

      close(fd1[1]);   //关闭通道

    close(fd2[0]);

  }

   

  return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐