1、进程间通信-PIPE(无名管道)

1、在子进程中写入数据,在父进程中读取数据

code:

#include<stdio.h> #include<stdlib.h> #include<unistd.h> int main() { pid_t pid; int temp; int pipedes[2]; char s[14]="Jason's message"; char d[14]; if((pipe(pipedes))==-1){ perror("pipe"); exit(EXIT_FAILURE); } if((pid=fork())==-1){ perror("fork"); exit(EXIT_FAILURE); } else if(pid==0){ // child process printf("now, write data to the pipe/n"); if(write(pipedes[1],s,14)==-1){ perror("write"); exit(EXIT_FAILURE); } else{ printf("the data I wrote is:%s/n",s); exit(EXIT_SUCCESS); } } else if(pid>0){ sleep(2); printf("now read data from pipe/n"); if((read(pipedes[0],d,14))==-1){ perror("read"); exit(EXIT_FAILURE); } printf("the data from pipe is %s/n"); } return 0; }

结果:

now, write data to the pipe
the data I wrote is:Jason's messag
now read data from pipe
the data from pipe is Jason's messag

 

2、使用dup2函数,将标准输出重定向到某文件

code:

#include<unistd.h> #include<stdio.h> #include<errno.h> #include<fcntl.h> #include<string.h> #include<sys/types.h> #include<sys/stat.h> #include<stdlib.h> #define BUFFER_SIZE 1024 int main(int argc,char * argv[]) { int fd; char buffer[BUFFER_SIZE]; if(argc!=2){ fprintf(stderr,"Usage:%s filename/n",argv[0]); exit(EXIT_FAILURE); } //打开重定向文件 if((fd=open(argv[1],O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR))==0){ fprintf(stderr,"Open %s Error:%s/n",argv[1],strerror(errno)); exit(EXIT_FAILURE); } //重定向输出设备 if(dup2(fd,fileno(stdout))==-1){ fprintf(stderr,"Redirect Error:%s/n",strerror(errno)); exit(EXIT_FAILURE); } printf("this is Jason/n"); return 0; }

结果:

root@ubuntu:/code/chap8# ./run2 doc3
root@ubuntu:/code/chap8# cat doc3
this is Jason

 

3、实现 who|sort 命令

code:

#include<stdio.h> #include<sys/types.h> #include<unistd.h> #include<fcntl.h> #include<sys/wait.h> #include<stdlib.h> int main() { int fds[2]; if((pipe(fds))==-1){ perror("pipe"); exit(EXIT_FAILURE); } if(fork()==0){ //child sort char buf[128]; dup2(fds[0],0); close(fds[1]); execlp("sort","sort",(char*)0); } else{ if(fork()==0) { //child who dup2(fds[1],1); close(fds[0]); execlp("who","who",(char *)0); } else{ //main process close(fds[0]); close(fds[1]); wait(NULL); wait(NULL); } } return 0; }

结果:

root@ubuntu:/code/chap8# ./run3
root     pts/1        2010-11-23 11:58 (:0.0)
root     pts/2        2010-11-23 13:50 (:0.0)
root     tty7         2010-11-23 11:49 (:0)

你可能感兴趣的:(1、进程间通信-PIPE(无名管道))