linux进程无名管道通信
用于父子进程的通信
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
void pipe_read(int pipes[]);
void pipe_write(int pipes[]);
int main()
{
int pipes[2]; // 文件描述符,pipes[0] 读取, pipes[1] 写入
pid_t pid; // pid_t 宏定义
int rc;
/* 应该在创建子进程前创建管道 */
rc = pipe(pipes); // 创建管道, 若成功返回0, 否则返回-1
if(rc == -1){
perror("pipes\n");
exit(1);
}
pid = fork(); // fork()创建新进程,成功则返回两个值,子进程返回0, 父进程返回Id
// 否则出错返回-1
switch(pid){
case -1: // 出错
perror("fork\n");
exit(1);
case 0: // 子进程
pipe_read(pipes);
default: // 父进程
pipe_write(pipes);
}
return 0;
}
void pipe_read(int pipes[]) // 读数据
{
int c;
int rc;
close(pipes[1]); // 关闭写入
/* ssize_t read(int fd,void *buf,size_t count) */
while((rc = read(pipes[0], &c, 1)) > 0){
putchar(c);
}
close(pipes[0]);
exit(0);
}
void pipe_write(int pipes[]) // 写数据
{
int c;
int rc;
close(pipes[0]); // 关闭读取
while((c = getchar()) > 0){
rc = write(pipes[1], &c, 1);
if(rc == -1){
perror("Parent: write");
close(pipes[1]);
exit(1);
}
}
close(pipes[1]);
exit(0);
}