Linux系统编程之管道通信

    科技2022-08-30  102

    @TOC

    无名管道(半双工)

    局限性:

    数据自己读不能自己写。

    数据一旦被读走,便不在管道中存在,不可反复读取。

    由于管道采用半双工通信方式。因此,数据只能在一个方向上流动。

    . 只能在有公共祖先的进程间使用管道。 pipe的demo:

    #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> int main() { //int pipe(int pipefd[2]); int fd[2]; char *buf = NULL; buf = (char*)malloc(128); if(pipe(fd) == -1){ printf("creat pipe failed\n"); } pid_t pid = fork(); if(pid < 0){ //for>0为父进程 printf("creat process failed\n"); }else if(pid > 0){ printf("this is father process\n"); close(fd[0]); write(fd[1],"hello world", strlen("hello world")); wait(NULL); }else{ printf("this is child process\n"); close(fd[1]); read(fd[0],buf,128); printf("read form father %s\n",buf); exit(0); } return 0; }

    有名管道(全双工)

    特点:不相关的两个进程可以进行通信 FIFO的demo 读端兼创建命名管道:

    #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> int main() { // int mkfifo(const char *pathname, mode_t mode); char buf[1024] = {'\0'}; int n_read; if((mkfifo("./file",0600)==-1) && errno!=EEXIST){ printf("pipe failed\n"); perror("why"); } int fd = open("./file",O_RDONLY); printf("open success\n"); while(1){ n_read = read(fd,buf,512); printf("read %d byte,str:%s\n",n_read,buf); } close(fd); return 0; }

    写端:

    #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <string.h> int main() { int cnt = 0; char *str = "messag from fifo"; int fd = open("./file",O_WRONLY); printf("write open success\n"); while(1){ write(fd,str,strlen(str)); sleep(1); cnt++; //printf("%d\n",cnt); if(cnt==5){ break; } } close(fd); return 0; }
    Processed: 0.010, SQL: 9