1.Pipe函数与进程通信
下面实验为使用管道进行父子进程间通信。程序首先判断参数是否合法,因为输入的字符将从父进程通过发送到子进程中。然后,调用pipe函数创建父子进程用于通信的管道。使用fork函数创建子进程时,子进程会获得与父进程相同的资源,其中包括文件描述符信息。因此,调用fork函数须在pipe函数调用前。
当父子进程通过管道进行通信时,files[1]为用于数据写入的文件描述符.因此,在子进程中,要读取管道中的数据可以调用read函数,而读取得文件描述符为files[0]。对于父进程而言,写入数据需要调用write函数,要写入的文件描述为files[1]。
#include #include int main(int argc,char* argv[]) { int f_des[2]; int pid; char msg[BUFSIZ]; if(argc!=2){ printf("Usage: %s message\\n",argv[0]); return 1; } if(pipe(f_des)==-1){ perror("cannot create the IPC pipe"); return 1; } pid=fork(); if(pid==-1){ perror("cannot create new process"); return 1; }else if(pid==0){ close(f_des[1]); if(read(f_des[0],msg,BUFSIZ)==-1){ perror("child process cannot read data from pipe"); return 1; }else printf("in child process, receive message: %s\\n",msg); _exit(0); }else { close(f_des[0]); if(write(f_des[1],argv[1],strlen(argv[1]))==-1){ perror("parent process cannot write data to pipe"); return 1; }else printf("in parent process, send message: %s\\n",argv[1]); wait(NULL); _exit(0); } return 0; } 2. Shell管道重订向的实现 实现了在SHELL中的两个命令的组合。如:“Is|less”可以实现文件列表的分页显示,程序实现的泪是命令为 “Is more”.是通过调用dup2函数,将创建的管道的读写文件描述符重定向到标准输入输出。 #include #include int main(int argc,char* argv[]) { int f_des1[2]; int f_des2[2]; int pid; char msg[BUFSIZ]; char p_msg[BUFSIZ]; if(argc!=2){ printf("Usage: %s message\\n",argv[0]); return 1; } if(pipe(f_des1)==-1){ perror("cannot create the IPC pipe"); return 1; } if(pipe(f_des2)==-1){ perror("cannot create the IPC pipe"); return 1; } pid=fork(); if(pid==-1){ perror("cannot create new process"); return 1; }else if(pid==0){ close(f_des1[1]); close(f_des2[0]); //read data from the parent process if(read(f_des1[0],msg,BUFSIZ)==-1){ perror("child process cannot read data from pipe"); return 1; }else printf("in child process, receive message: %s\\n",msg); //write data to the parent process if(write(f_des2[1],msg,strlen(msg))==-1){ perror("child process cannot write data to pipe"); return 1; }else printf("in child process, send message back: %s\\n",argv[1]); _exit(0); }else { close(f_des1[0]); close(f_des2[1]); //write data to the child process if(write(f_des1[1],argv[1],strlen(argv[1]))==-1){ perror("parent process cannot write data to pipe"); return 1; }else printf("in parent process, send message: %s\\n",argv[1]); //read data from the cild process if(read(f_des2[0],p_msg,BUFSIZ)==-1){ perror("parent process cannot read data from pipe"); return 1; }else printf("in parent process, receive message: %s\\n",p_msg); wait(NULL); _exit(0); } return 0; }下载本文