1.管道的概念
管道是单向的、先进先出的,它把一个进程的输出和另一个进程的输入连接在一起。
一个进程(写进程)在管道的尾部写入数据,另一个进程(读进程)从管道的头部读出数据。
数据被一个进程读出后,将被从管道中删除,其它读进程将不能再读到这些数据。
管道提供了简单的流控制机制,进程试图读空管道时,进程将阻塞。同样,管道已经满时,进程再试图向管道写入数据,进程将阻塞
管道包括无名管道和有名管道两种,前者用于父进程和子进程间的通信,后者可用于运行于同一系统中的任意两个进程间的通信。
//无名管道#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int main(){ int pipe_fd[2]; pid_t pid; if(pipe(pipe_fd)<0){ perror("pipe"); return 1; } pid = fork(); if(pid==0){ sleep(3); char buf[128]; memset(buf,'\0',strlen(buf)); printf("%d",strlen(buf)); if(read(pipe_fd[0],buf,128)!=-1){ printf("child recv str:%s\n",buf); } exit(0); }else{ char* str = "jenkin"; char* str1 = "jenkin1"; if(write(pipe_fd[1],str,strlen(str))!=-1){ printf("parent write str : %s\n",str); } if(write(pipe_fd[1],str1,strlen(str1))!=-1){ printf("parent write str : %s\n",str1); } waitpid(pid,NULL,0); close(pipe_fd[0]); close(pipe_fd[1]); } return 0; }
//有名管道A
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> int main(){ if (mkfifo ("myfifo", 0666) == -1) { perror ("mkfifo"); exit (EXIT_FAILURE); } int fd = open ("myfifo", O_RDWR, 0666); if (fd == -1) { perror ("open"); exit (EXIT_FAILURE); } char text[] = "this is jenkin test"; size_t towrite = strlen(text); ssize_t written = write (fd, text, towrite); if (written == -1) { perror ("write"); exit (EXIT_FAILURE); } sleep(10); if (close (fd) == -1) { perror ("close"); exit (EXIT_FAILURE); } if (unlink ("myfifo") == -1) { perror ("unlink"); exit (EXIT_FAILURE); } return 0; }
//有名管道B
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> int main(){ int fd = open ("myfifo", O_RDWR, 0666); if (fd == -1) { perror ("open"); exit (EXIT_FAILURE); } char text[1024]; ssize_t readed = read (fd, text, 1024); if (readed == -1) { perror ("read"); exit (EXIT_FAILURE); } printf("%s\n", text); if (close (fd) == -1) { perror ("close"); exit (EXIT_FAILURE); } return 0; }