赞
踩
管道
管道的概念:
管道是一种最基本的IPC机制,作用于有血缘关系的进程之间,完成数据传递。调用pipe系统函数即可创建一个管道。有如下特质:
int pipe(int pipefd[2]);
返回值为-1则创建管道失败
示例1:创建一个父子进程,父进程向管道写入一个字符串,子进程再从管道中将字符串读出来并打印。
#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> int main() { int fd[2]; char buff[20]; pid_t pid; if(pipe(fd) < 0){ //creat pipe printf("create pipe error\n"); } pid = fork();创建父子进程 if(pid < 0){ // 父子进程创建失败 printf("fork error\n"); }else if(pid > 0){//父进程 sleep(3); printf("this is father\n"); close(fd[0]);关闭读端 write(fd[1], "lizehao henshuai", strlen("lizehao henshuai")); wait(); }else{//pid等于0创建子进程 printf("this is child\n"); close(fd[1]);关闭写端 int n_read = read(fd[0], buff, 20); printf("read %d byte buf:%s\n",n_read, buff); exit(0); } return 0; }
二、创建有名管道mkfifo
创建有名管道一个进程将字符串写入管道中在创建一个文件读出写入的字符串
mkfifo函数原型:int mkfifo(const char *pathname, mode_t mode); #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> int main() { int fd; char buf[30]; if(mkfifo("./file", 0600) == -1 && errno != EEXIST){//创建有名管道当返回值为-1 errno的不等于eexist的时候不等于EEXIST printf("creat fifo error\n"); perror("why"); } fd = open("./file", O_RDONLY);打开创建的管道 int n_read = 0; while(1){ n_read = read(fd, buf, 30); printf("read %d byte, context:%s\n", n_read, buf); } close(fd); return 0; }
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> int main() { int fd; int cnt =0; char *str = "from wite fifo"; fd = open("./file",O_WRONLY); printf("write open succese\n"); while(1){ write(fd, str, strlen(str)); sleep(1); if(cnt == 3){ break; } cnt++; } close(fd); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。