pipe()学习
例1: 进程内读写管道,代码如下:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <sys/stat.h> #include <unistd.h> #include <sys/types.h> #include <errno.h> #include <signal.h> int main(int argc, char *argv[]) { int fd[2]; pipe(fd); char s[100] = "hello pipe...."; while(1) { write(fd[1],s,100); bzero(s,100); read(fd[0],s,100); puts(s); sleep(1); } return 0; }
编译/链接执行后的结果如下:
例2: 进程间读写管道,代码如下:
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/stat.h> #include <unistd.h> #include <sys/types.h> #include <errno.h> #include <signal.h> void child_rw_pipe(int rfd,int wfd) { char msg[] = "from child process!!!\n"; write(wfd,msg,sizeof(msg)); char msg2[100]; read(rfd,msg2,100); printf("child read from pipe: %s\n",msg2); } void parent_rw_pipe(int rfd,int wfd) { char msg[] = "from parent process!!!\n"; write(wfd,msg,sizeof(msg)); char msg2[100]; read(rfd,msg2,100); printf("parent read from pipe: %s\n",msg2); } int main(int argc, char *argv[]) { int fd1[2]; int fd2[2]; pipe(fd1); pipe(fd2); pid_t pid = fork(); if(pid == 0) { close(fd1[1]); close(fd2[0]); child_rw_pipe(fd1[0],fd2[1]); exit(0); } close(fd1[0]); close(fd2[1]); parent_rw_pipe(fd2[0],fd1[1]); wait(NULL); return 0; }
父子进程分别向管道写数据, 从管道读数据. 编译/链接/执行,结果如下:
例3: 父子进程间读写管道:
父进程将命令行数据写入管道, 代码如下:
#include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <termios.h> #include <signal.h> int main(int argc,char *argv[]) { int fd[2]; pid_t pid; pipe(fd); pid = fork(); if(pid == 0) { close(fd[1]); close(0); dup(fd[0]); execl("process","process",NULL); exit(0); } close(fd[0]); write(fd[1],argv[1],strlen(argv[1])); wait(NULL); return 0; }
子进程读出管道内容(前面代码dup(fd[0])将文件描述符STDIN_FILENO重定向到管道的读端), 代码如下:
#include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <termios.h> #include <signal.h> int main(int argc,char *argv[]) { while(1) { char buf[100]; int ret = read(STDIN_FILENO,buf,100); if(ret > 0) { buf[ret] = 0; printf("process receive: %s\n",buf); if(strcmp(buf,"exit") == 0) exit(0); if(strcmp(buf,"getpid") == 0) { printf("child pid = %d\n",getpid()); exit(0); } } } return 0; }
编译/链接/执行, 结果如下:
原文:http://www.cnblogs.com/zhanglong71/p/5081103.html