UNIX commands in C

Robert Earl rearl at gnu.ai.mit.edu
Thu May 2 01:39:57 AEST 1991


In article <24527 at well.sf.ca.us> ron at well.sf.ca.us (Ronald Hayden) writes:
|
|   There are actually several ways to do this (check out the book C
|   Programming In a UNIX Environment for a complete discussion), but for
|   a simple command such as "who", you can simply:
|
|
|   #include <stdio.h>
|
|   main ()
|   {
|    printf("\nTesting the UNIX 'who' command --\n");
|    system("who");
|    printf("\nDone.\n");
|    exit(1);
|   }

Since system() [and popen()] does an implicit fork, it's good practice
to explicitly flush output buffers before you call this routine;
otherwise you end up with possibly duplicated or misleading output.
For instance, here's what I get when I redirect the output of this
program to a file (block buffered):

	guest    ttyp1    May  1 09:59 (192.35.86.25)
	rearl    ttyp4    May  1 11:05 (dialin.ucsd.edu)
	ggray    ttyp6    May  1 10:43 (geech)
	guest    ttyp8    May  1 11:20 (192.35.86.26)
	
	Testing the UNIX 'who' command --
	
	Done.
	
Probably not what you intended.  Add "fflush(stdout)" or
"fflush(NULL)" (to flush all buffers) before calling system().  I
think this is a FAQ in one group or another...

By the way, any reason why this program was made to return failure?

--robert
rearl at gnu.ai.mit.edu
rearl at watnxt3.ucr.edu



More information about the Comp.lang.c mailing list