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

Linux 进程间通讯之创建无名管道和读写无名管道

2016-12-28 09:39 676 查看
Linux进程间通讯的方式:

1.     管道(pipe)和有名管道(FIFO).

2.     信号(signal)

3.     消息队列

4.     共享内存

5.     信号量

6.     套接字(socket)

 

 

管道通讯:

无名管道:由pipe()函数创建,int
pipe(int  filedis[2]), 当管道建立时有两个文件描述符,filedis[0]用于读管道,filedis[1]用于写管道。关闭管道,仅需将两个文件描述符关闭即可。

 

创建无名管道pipe()

#include <unistd.h>

#include <stdio.h>

 

int main(){

         intpipe_filed[2];

         if(pipe(pipe_filed)<0){

                   printf("pipecreate failed.\n");

                   return-1;

         }

         else{

                   printf("pipecreate successfully.\n");

                  close(pipe_filed[0]);                            //关闭相应读管道(必须要)

                   close(pipe_filed[1]);                            //关闭相应写管道(必须要)

         }

}

 

注:fork()必须在pipe()之前来创建子进程,否则子进程无法进程相应的文件描述符,如果在fork之后,那么fork会在子/父进程各执行一次,属不同的管道。

 

读写无名管道示例:

#include <stdio.h>

#include <unistd.h>

#include <string.h>

#include <sys/wait.h>

 

int main(){

         charcache[100];

         intfiledis[2];

         if(pipe(filedis)< 0){

                   printf("Createpipe failed.\n");

                   return-1;

         }

         memset(cache,0, sizeof(cache));            //在一段内存块中填充某个特定的值,此为,对cache数组以0进行填充

 

         intpid;

         pid= fork();                                            // 创建子进程

         if(pid== 0){                                            //     进入子进程

                   printf("Inchild process.\n");

                   close(filedis[1]);                          //     关闭写管道

                   sleep(3);                                        //     等待,为了等父进程写入东西

                   read(filedis[0],cache, 100);     //     读管道,并将内容写入cache之中

                   printf("%s.\n",cache);              //     打印cache内容

                   close(filedis[0]);                          //     关闭读管道

         }

         elseif(pid > 0){                             //     进入父进程

                   printf("Inparent process.\n");

                   close(filedis[0]);                          //     关闭读管道

                   write(filedis[1],"Hello ",6);     //     第一次写入

                   write(filedis[1],"linuxdba", 8);         //     第二次写入

                   close(filedis[1]);                          //     关闭写管道

                   wait(NULL);                                  //     等待子进程退出再往下执行

         }

         else{

                   printf("Createchild process failed.\n");

                   return-1;

         }

         return0;

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