进程间管道通信基础

xiaoxiao2021-02-28  21

练习:使用管道实现兄弟进程间通信。 兄:ls 弟: wc -l 父:等待回收子进程。 要求,使用“循环创建N个子进程”模型创建兄弟进程,使用循环因子i标示。注意管道读写行为


#include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main() { int ret,i,num =2; int fd[2]; pid_t pid,w_pid; int status; if ( -1 == (ret = pipe(fd) )) { perror("pipe faile"); exit(1); } for(i = 1; i < 3; i++) { pid = fork(); if(0 == pid) break; } //兄 写,弟 读 if( 0 == pid ) { //兄 if(1 == i) { close(fd[0]); dup2(fd[1],STDOUT_FILENO);//作为管道输入 execlp("ls","ls",NULL); } //弟 if( 2 == i) { close(fd[1]); dup2(fd[0],STDIN_FILENO); execlp("wc","wc",NULL); } } else { #if 0 close(fd[0]); close(fd[1]); for(i=0; i<2; i++) wait(NULL); #endif #if 1 //轮循方式回收子进程 do { close(fd[0]); close(fd[1]); w_pid = waitpid(-1,NULL,WNOHANG); if(w_pid > 0) num--; }while(num>0); printf("finished\n"); #endif } return 0; }
转载请注明原文地址: https://www.6miu.com/read-250244.html

最新回复(0)