• linux IPC的PIPE


    一、PIPE(无名管道)

    函数原型:

    #include <unistd.h>
    
    int pipe(int fd[2]);

    通常,进程会先调用pipe,接着调用fork,从而创建从父进程到子进程的IPC通道。

    父进程和子进程之间也可用通过pipe通信。

    例子,父进程到子进程hello world:

     1 #include "apue.h"
     2 
     3 int main(void)
     4 {
     5         int n;
     6         int fd[2];
     7         pid_t pid;
     8         char line[MAXLINE];
     9 
    10         if(pipe(fd) < 0)
    11                 err_sys("pipe error");
    12         if((pid = fork()) < 0) {
    13                 err_sys("fork error");
    14         } else if (pid > 0) {
    15                 close(fd[0]);
    16                 write(fd[1], "hello world
    ", 12);
    17         } else {
    18                close(fd[1]);
    19               n = read(fd[0], line, MAXLINE);
    20                write(STDOUT_FILENO, line, n);
    21         }
    22         exit(0);
    23 }

    二、函数popen和pclose

    #include <stdio.h>
    
    FILE *open(const char *cmdstring, const char *type);
    
    int pclose(FILE *fp);

    创建一个管道,fork一个子进程,关闭未使用的管道端,执行一个shell运行命令,然后等待命令终止。

    #include "apue.h"
    #include <stdio.h>
    
    int main()
    {
        FILE *fp;
        char ch, line[300];
    
        fp = popen("ls *.c", "r");
        if(fp != NULL)
        {
            while(fgets(line, 300, fp))
            {
                printf("line=%s
    ", line);
            }
        }
    
        pclose(fp);
    
        return 0;
    }
    无欲速,无见小利。欲速,则不达;见小利,则大事不成。
  • 相关阅读:
    django 中 slice 和 truncatewords 不同用法???
    js如何获取到select的option值???
    MySQL的btree索引和hash索引的区别
    Python3之Django Web框架中间件???
    2019.07.25考试报告
    2019.07.19考试报告
    2019.07.18考试报告
    2019.07.16考试报告
    2019.07.12考试报告
    ELK+Kafka
  • 原文地址:https://www.cnblogs.com/ch122633/p/8058671.html
Copyright © 2020-2023  润新知