Unix pipes: example 2

/* This sample program creates the same affect as typing ps -aux|grep <username> */ #include <stdio.h> char *getlogin(); main() { FILE *fp; int pipefds[2]; int pid; char *username; if((username = getlogin()) == NULL) { fprintf(stderr, "myps: user name not set.\n"); exit(1); } if(pipe(pipefds) < 0) { perror("myps"); exit(1); } if((pid = fork()) < 0) { perror("myps"); exit(1); } if(pid == 0) { /* close standard input */ close(0); /* duplicate our pipe to be standard input */ dup(pipefds[0]); /* close the pipe */ close(pipefds[0]); close(pipefds[1]); execl("/bin/grep", "grep", username, (char *) 0); perror("myps"); exit(1); } /* close the read file descriptor */ close(pipefds[0]); /* close standard output */ close(1); /* duplicate the write file descriptor to std out */ dup(pipefds[1]); /* close the write file descriptor */ close(pipefds[1]); fp = fdopen(pipefds[1], "w"); execl("/bin/ps", "ps", "-aux", (char *) 0); perror("myps"); exit(1); }


Send email to cs153@csif.cs.ucdavis.edu.

Department of Computer Science
University of California at Davis
Davis, CA 95616-8562



Page last modified on 1/23/97