Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 1993 > July - August

Using the UNIX Pipe in C

Ed Schaefer

Sidebar

Virtually all UNIX system administrators exploit the power and convenience offered by pipes when they are working from the command line or writing shell script. By connecting general purpose filters with pipes, the system administrator can quickly generate tidy custom reports and analytic tools without the overhead and housekeeping problems associated with myriad temporary files.

The pipe with all its advantages is also available in C (using the standard library functions popen() and pipe()), but, typically system administrators are less inclined to use pipes in their C programs. In this article I'll first explain how to use popen() from within a C program to read directly from the output of another program. Then I'll present two more general C functions - one for reading from the pipe and one for writing to the pipe - and use these functions to illustrate how pipes are used from within a C program.

The popen() Example

The popen() function allows a C program to spawn a task and then attach itself to the input or output of that task - which is most commonly a set of pipelined commands. In its simplest application, the popen() function allows you to connect a special purpose C program to a sequence of standard commands without writing a separate piece of shell script. For example, if a special usage report required you to analyze a sorted list of current users, you could either write a shell script to generate and sort the list and pipe the results into a special C program which performs the analysis:

who | sort | analyze

or you could avoid the separate script file by using popen(). The call

input_stream = popen( "who | sort", "r")

executes the pipelined task "who|sort" and connects its output (in read mode - r) to the pipe input_stream.




MarketPlace

"Six Sigma" Certification
Villanova Six Sigma Certification 100% Online Program - Free Info.

Project Management-Online
Nation's Leading Online PMP Course From Villanova-Find Out More Now.

BugSplat - Automatic Crash Analysis
Fast online exception analysis. Capture customer crash data online.

Flowcharts from C/C++ code -- Free trial download
Understand C/C++ code in less time. A new team member ? Inherited legacy code ? Get up to speed faster with Crystal Flow for C/C++. Code-formatting improves readability. Flowcharts are integrated with code browser. Export flowcharts to Visio.

Wanna see your ad here?