- #include "apue.h"
- static void sig_pipe(int); /* our signal handler */
- int main(void)
- {
- int n,fd1[2],fd2[2];
- pid_t pid;
- char line[MAXLINE];
- if (signal(SIGPIPE,sig_pipe) == SIG_ERR)
- err_sys("signal error ");
- if ( pipe(fd1) < 0 || pipe(fd2) < 0)
- err_sys("pipe error ");
- if (( pid = fork() ) < 0) {
- err_sys("fork error ");
- } else if ( pid > 0) { /* parent */
- close(fd1[0]);
- close(fd2[1]);
- while( fgets(line,MAXLINE,stdin) != NULL ){
- n = strlen(line);
- if (write(fd1[1],line,n) != n)
- err_sys("write error to pipe");
- if (( n = read(fd2[0],line,MAXLINE)) < 0)
- err_sys("read error form pipe ");
- if ( n == 0 ){
- err_msg("child closed pipe ");
- break;
- }
- line[n] = 0; /* null terminate */
- if (fputs(line,stdout) == EOF )
- err_sys("fputs error");
- break;
- }
- if (ferror(stdin))
- err_sys("fgets error on stdin ");
- exit(0);
- }else { /* child */
- close(fd1[1]);
- close(fd2[0]);
- if (fd1[0] != STDIN_FILENO) {
- if (dup2(fd1[0],STDIN_FILENO) != STDIN_FILENO)
- err_sys("dup2 error to stdin");
- close(fd1[0]);
- }
- if (fd2[1] != STDOUT_FILENO) {
- if (dup2(fd2[1],STDOUT_FILENO) != STDOUT_FILENO)
- err_sys("dup2 error to stdout ");
- close( fd2[1]);
- }
- if (execl("./add","add",(char *) 0) < 0)
- err_sys("execl error");
- }
- exit(0);
- }
-
- static void
- sig_pipe(int signo){
- printf("sigpipe caught \n");
- exit(1);
- }
- #include "apue.h"
- int
- main(void )
- {
- int n ,int1,int2;
- char line[MAXLINE];
- while((n=read(STDIN_FILENO,line,MAXLINE)) > 0) {
- line[n]=0; /* null terminate */
- if (sscanf(line,"%d%d",&int1,&int2) == 2){
- sprintf(line,"%d\n",int1+int2);
- n=strlen(line);
- if (write(STDOUT_FILENO,line,n) != n)
- err_sys("write error");
- } else {
- if (write(STDOUT_FILENO,"invalid args \n",13) != 13)
- err_sys("write error");
- }
- }
- exit(0);
- }
output of process :
./c15-9
2 4
6
./15-9
然后打开一个新的终端
ps aux
kill add
在换回原终端
2 4
sigpipe caught
通过使用两个管道来连接一个协同进程。
程序的流程如下:
fd1[0]
父进程 ---------------》 子进程
《------------
fd2[1]
父进程的标准输入和输出均被定向到了管道的两端,通过两个管道来实现
阅读(1434) | 评论(0) | 转发(0) |