Wednesday, November 12, 2014

Unix Prog: popen, pclose(3)

1. Filter Program

We'll build two process piped up together in following way:

2. Source code:
filter.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<ctype.h>  
   
 int main(int argc, char *argv[])  
 {  
  int c;  
   
  while((c = getchar()) != EOF) {  
   if(isupper(c)) c = tolower(c);  
   if(putchar(c) == EOF) {  
    printf("output error!\n");  
    exit(1);  
   }  
   if(c == '\n')  
    fflush(stdout);  
  }  
   
  exit(0);  
 }  

main.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<sys/wait.h>  
   
 int main(int argc, char* argv[])  
 {  
  char line[20];  
  FILE * fpin;  
   
  // Open the filter.out, fpin is used to read input from filter.out  
  if((fpin = popen("./filter.out", "r")) == NULL) {  
   printf("popen error!\n");  
   exit(1);  
  }  
   
  // Make a loop to read from the filter.out and output to standard output  
  for(;;) {  
   fputs("prompt>", stdout);  
   fflush(stdout);  
   if(fgets(line, 20, fpin) == NULL) break;  
   if(fputs(line, stdout) == EOF) {  
    printf("fputs error to pipe\n");  
    exit(2);  
   }  
  }  
   
  // close the stream  
  if(pclose(fpin) == -1) {  
   printf("pclose error!\n");  
   exit(3);  
  }  
   
  putchar('\n');  
  exit(0);  
 }  

shell:
After running the program, user provide input at terminal. And filter read its input, convert the string into lowercase and then transfer to main.out.
If user type Ctrl D, main.out will read the NULL from filter.out and program exits.
 ubuntu@ip-172-31-23-227:~$ ./main.out  
 prompt>HELLO WORLD!  
 hello world!  
 prompt>  

No comments:

Post a Comment