父子进程管道通信
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdio.h>
/*
* 功能:父进程通过管道传输两个数据给子进程
* 由子进程负责从管道读取并输出
*/
int main(void){
int fd[2]; //父子进程都会有一份fd[0](读管道) fd[1](写管道)
//pipe系统调用创建管道
if(pipe(fd) < 0){
perror("pipe error");
exit(1);
}
pid_t pid;
if((pid = fork()) < 0){
perror("fork error");
exit(1);
} else if(pid > 0){ //父进程
close(fd[0]); //父进程需要写数据,关掉读管道
//往管道中写数据
int start = 1 , end = 100;
write(fd[1],&start,sizeof(int));
write(fd[1],&end,sizeof(int));
close(fd[1]); //写完关掉管道
wait(0); //等待子进程结束
} else{ //子进程
close(fd[1]); //子进程需要读数据,关掉写管道
int start , end;
read(fd[0],&start,sizeof(int));
read(fd[0],&end,sizeof(int));
close(fd[0]); //读完关掉管道
//打印获得的数据
printf("start:%d end:%d",start,end);
}
}
管道命令实现
#include "unistd.h"
#include "stdlib.h"
#include "stdio.h"
#include "sys/wait.h"
char *cmd1[3] = {"cat", "D:/HUAWEI-Cpp/passwd.txt", NULL}; //cat 命令默认输出是屏幕,所以需要将标准输出重定向到管道的写端,采用dup2命令
char *cmd2[3] = {"grep", "root", NULL}; //grep 命令默认读取的来源是标准输入
//char *cmd2[3] = {"wc", "-l", NULL};
int main(void){
int fd[2];
if((pipe(fd)) < 0){
perror("pipe error");
exit(1);
}
pid_t pid;
//创建进程扇,两个子进程负责通信
for(int i = 0;i < 2;i ++){
pid = fork();
if(pid < 0){
perror("fork error");
exit(1);
}else if(pid == 0){ //child process
if(i == 0){ //第一个子进程负责往管道写入数据
close(fd[0]);
//重定向到管道写端
dup2(fd[1],STDOUT_FILENO);
//调用exec函数执行cat命令
execvp(cmd1[0],cmd1);
close(fd[1]);
break;
}
if(i == 1){ //第二个子进程负责往管道读入数据
close(fd[1]);
//重定向到管道的读端
dup2(fd[0],STDIN_FILENO);
//调用exec函数执行grep命令
execvp(cmd2[0],cmd2);
close(fd[0]);
break;
}
}else{ //parent process
if(i == 1){
//父进程在这个功能里只负责创建两个子进程,不需要其他操作
close(fd[0]);
close(fd[1]);
//父进程要等到子进程全部创建完才能回收
wait(0);
wait(0);
}
}
}
}