16.进程间的通信:管道

xiaoxiao2021-02-28  156

1.popen(), pclose() 2.pipe() 2.1 普通 pipe 2.2 父子进程 pipe 2.3 不同进程 pipe 2.4 用管道当作 标准输入,标准输出 2.5 命名管道

1.什么是管道

2.进程管道

3.将输出送往 popen

4.pipe 调用

#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> int main() { int data_processed; int file_pipes[2]; const char some_data[] = "123"; char buffer[BUFSIZ + 1]; pid_t fork_result; memset(buffer, '\0', sizeof(buffer)); if (pipe(file_pipes) == 0) { fork_result = fork(); if (fork_result == -1) { fprintf(stderr, "Fork failure"); exit(EXIT_FAILURE); } // We've made sure the fork worked, so if fork_result equals zero, we're in the child process. if (fork_result == 0) { data_processed = read(file_pipes[0], buffer, BUFSIZ); printf("Read %d bytes: %s\n", data_processed, buffer); exit(EXIT_SUCCESS); } // Otherwise, we must be the parent process. else { data_processed = write(file_pipes[1], some_data, strlen(some_data)); printf("Wrote %d bytes\n", data_processed); } } exit(EXIT_SUCCESS); }

5.父进程和子进程


命名管道:FIFO

把管道做标准输入和标准输出: 好处是 可以调用标准程序,即那些不需要以文件描述符作为参数的程序 先关闭标准输入,然后用 dup() 函数 管道有长度限制: PIPE_BUF 一个管道,多个写进程的话,必须保持写请求是发往一个阻塞的 FIFO,并且每次写请求的数据长度小于等于 PIPE_BUF 字节,系统就能保证写数据不会交错在一起。

转载请注明原文地址: https://www.6miu.com/read-18487.html

最新回复(0)