Documented in Volume 1 of the UNIX Programmers Manual.
% cc x.c -o x
will compile the C program text in file x.c and store an executable
(-o) into the file named x in the current directory.
From: Dave Curry Purdue University
Coredump Message Meanings
bus error
- Types of arguments and parameters don't match.
- I/O problems - reading past EOF, reading a closed file, bad file
pointers, etc. [This apparently refers to stdio only.]
- Arrays improperly dimensioned. Eg., attempting to access a word
starting at an odd address.
- Referencing a non-existent bus device.
- NULL or uninitialized pointer, subscript out of range.
memory fault
- Subscripting arrays past the memory allocation for your program.
- NULL or uninitialized pointer, subscript out of range.
- Attempts to reference data outside valid address space
- Parity errors in address space
- Recursion (try making your own routines "read" and "write" and
then call "scanf" or "printf" and watch what happens).
IOT trap
- Execution of IOT (I/O Trap) instruction; also used by the "abort"
routine (PDP-11's only).
EMT trap
- Emulator Trap Instruction (PDP-11's).
trace/BPT trap
- Execution of the BPT instruction (PDP-11's)
- Trace bit set in Processor Status (long) Word
- Trying to tell the program to go to an address that doesn't exist.
- "Wanton destruction caused execution of data or trashing of
instructions."
floating exception
- Invalid floating point operation:
- overflow
- underflow
- divide by zero
- log of negative number
- float-to-int conversion overflow
segmentation fault
- Subscript out of range.
- Handing "printf", etc. a string which is not NULL terminated.
illegal instruction
- Attempt to execute a privileged instruction, such as "halt".
- Execution of nonsense instruction (e.g., jump to a register).
- Forgot -f flag to cc on PDP-11 without floating point hardware.
Special Note: John Bruner also had this to say about Illegal
Instruction:
"On the VAXes the 'abort' routine executes a 'halt' and blows away the
program with an illegal instruction.
Note that SIGTRAP (trace trap) and SIGILL (illegal instruction trap)
are not reset when caught. Thus, a generalized trap handler such as
sig(s)
int s;
{
fprintf(stderr,"Fatal signal %d\n",sig);
abort();
}
will (on the VAX) recursively call 'abort' which will attempt to execute
a 'halt' [illegal] and trap to 'sig' which will call 'abort'... until
you either kill it with a signal it doesn't catch (e.g. SIGKILL=9) or it
runs out of stack space (a LONG time on the VAX)."
Calling vi from C, (G. Sloane, Apr 85):
/* PROGRAM: callvi.c */
#include /* for NOFILE param. (max number of open files */
#include /* union for wait's status */
#include /* I/O definitions */
main() /* Driver */
{
char filename[128];
printf("\nEnter filename: ");
gets(filename);
invoke("/usr/ucb/vi", filename);
printf("\nThanks.\n");
} /* END DRIVER */
/**************************************************************/
/* Invoke a program with ONE argument as a child process */
/**************************************************************/
static invoke(prog, arg)
char *prog, *arg;
{
int s;
/* declare definition of wait's status */
/* a la sys/wait.h and implicitly allocate storage for it */
union wait status;
if(vfork() == 0) /* child */
{ /* close descriptors ourselves, preserve std[in, out, err] */
for(s=3; s<=NOFILE; s++)
(void)close(s);
/* invoke the program with ONE argument */
execl(prog, prog, arg, 0);
/* terminate the child process */
_exit(-1);
}
else /* parent */
{ /* check wait's status */
(void)wait(&status);
if(status.w_retcode!= 0)
/* return code is error */
printf("\nProgram %s failed...\n", prog);
}
} /* END PROGRAM*/
Read from a pipe, (S. Kemp May 85):
/* PROGRAM: pread.c */
#include
#include
main()
{
FILE *fp, *popen();
char cmdline[80];
char line[80];
/* fgrep -i for string) */
(void)strcpy(cmdline,"fgrep -i "); /* the command to do */
(void)strcat(cmdline,"fp "); /* the string to seek */
(void)strcat(cmdline,"/ga/kemp/x"); /* the filename to search */
fp = popen(cmdline, "r"); /* open pipe */
while (fgets (line, 80, fp)!=NULL) /* read lines from pipe */
printf("%s",line); /* report hits */
(void)pclose(fp); /* close pipe */
exit(0);
} /* END PROGRAM */
Read in RAW mode, (W. Harris and G. Sloane, May 85):
/* PROGRAM: getit.c
This C pgm allows a single character to be entered without hitting
return. It sets raw mode by setting CBREAK mode, accepts a character,
and then resets the tty to COOKED mode (by turning off CBREAK).
This was written by Wayne Harris and Gary Sloane.
Compile it as follows:
% cc -o getit getit.c
*/
#include
#include
#include
main()
{
char c;
struct sgttyb ttystate;
/* read the current status from the driver */
if(ioctl(fileno(stdin), TIOCGETP, (char *)&ttystate) != 0)
{
perror("Error: Failed to get current driver status word");
exit(0);
}
ttystate.sg_flags = ttystate.sg_flags | CBREAK; /* turn on CBREAK */
/* write out the changes to the driver */
if(ioctl(fileno(stdin), TIOCSETP, (char *)&ttystate) != 0)
{
perror("Error: CBREAK was not turned on");
exit(0);
}
printf("Enter a character (not DELETE):%c", c); /* prompt for character */
c = getchar(); /* do input in cbreak mode */
ttystate.sg_flags=ttystate.sg_flags & ~CBREAK; /* turn off CBREAK */
/* write out the changes to the driver */
if(ioctl(fileno(stdin), TIOCSETP, (char *)&ttystate) != 0)
{
perror("Error: CBREAK was not turned off");
exit(0);
}
printf("\nThe character received was:%c\n", c); /* print character received */
} /* END PROGRAM */
Traverse a UNIX directory, (Gary K. Sloane, Sep 84)
/*
Here is an example of how to use the C language to
traverse a directory and look at file names and types. Place
the following program in a file called subdirs.c and compile
it as follows: % cc -o subdirs subdirs.c
*/
#include
#include
#include
#include
DIR *opendir(), *dirp;
struct direct *dp, *readdr();
struct stat *buf;
char pathname[] = "./";
char *malloc(), *path;
int errno;
main()
{
path = malloc(256);
buf = (struct stat *)malloc(sizeof(struct stat));
dirp = opendir(pathname);
while((dp = readdir(dirp)) != NULL)
{
strcpy(path, pathname);
strcat(path, dp->d_name);
if(stat(path,buf) == -1)
{
printf("Call to *stat* failed...\n Errno: %d", errno);
exit(0);
}
if((buf->st_mode) & (u_short)0040000)
printf("Subdirectory found: %s\n", dp->d_name);
}
printf("Finished.\n");
}
The program uses the opendir call to open the current directory (".").
The while loop traverses all files in the directory, reading each entry
in turn into a structure called dp (via the readdir call).
The complete file pathname is built by catenating the filename
(dp->d_name) onto the directory name (pathname).
The stat system call is used to get information about that
file, and if the directory bit is set (in buf->st_mode as returned by
the stat call), the file name is printed out.
Upon reading all the file entries in the directory, the program
prints "Finished" and exits back to the shell.
gettimeofday example (G. Sloane, Sep 85)
/* Program for getting today's date */
#include
#include
main()
{
/* declare a string to hold the date in MM/DD/YY format */
char date[9];
/* call gettimeofday to load the date string */
today(date);
/* print today's date */
printf("Today is %s\n", date);
}
today(date)
char *date;
{
struct tm *localtime(),
*dt;
struct timeval tp;
/* get time in seconds since January 1, 1970 */
(void)gettimeofday(&tp,(struct timezone *)0);
/* get date and time and place in structure 'dt' */
dt = localtime((int *)&tp.tv_sec);
/* build the date in an ascii string */
dt->tm_mon += 1; /* months go 0-11 */
date[0] = dt->tm_mon / 10 + '0';
date[1] = dt->tm_mon % 10 + '0';
date[2] = '/';
date[3] = dt->tm_mday / 10 + '0';
date[4] = dt->tm_mday % 10 + '0';
date[5] = '/';
date[6] = dt->tm_year / 10 + '0';
date[7] = dt->tm_year % 10 + '0';
date[8] = '\0';
return;
}
/* End of Program */
From: lwall%sdcrdcf.uucp@BRL.ARPA (Larry Wall) news@brl-tgr.ARPA
Subject: Re: \"handy.h\"
Here's a chunk of code straight out of rn:
/* some handy defs */
#define bool char
#define TRUE (1)
#define FALSE (0)
#define Null(t) ((t)0)
#define Nullch Null(char *)
#define Nullfp Null(FILE *)
#define Ctl(ch) (ch & 037)
#define strNE(s1,s2) (strcmp(s1,s2))
#define strEQ(s1,s2) (!strcmp(s1,s2))
#define strnNE(s1,s2,l) (strncmp(s1,s2,l))
#define strnEQ(s1,s2,l) (!strncmp(s1,s2,l))
From Morris Kahn (...ihnp4!wucs!afinitc!msk)
Affinitec, Corp., 2252 Welsch Ind. Ct., St. Louis, MO 63146 (314)569-3450
Subject: Redirecting file descriptor 3 - SUMMARY OF RESPONSES (and thanks!)
I have received these ... responses to my original question on how
to redirect output to/from file descriptors other than 0 (stdin),
1 (stdout), and 2 (stderr).
Thank you all for your helpful information!
NOTE: Bourne shell only...
From ark@grigg:
--------------
#include
FILE *file3;
file3 = fdopen (3, "w");
if (file3 == NULL) { /* complain */ }
fprintf (file3, ...);
From mike@whuxl:
---------------
You can use any system calls directly on them. This includes raw
I/O (read, write), dup, ioctl, fcntl, lseek, close, etc. Just say
write(3, "hello", 5)
for instance. If you want to use the normal stdio routines, create a
FILE pointer to it using fdopen():
FILE *fp;
fp = fdopen(3, "w");
fprintf(fd, "blick is %d\n", blick);
...
If you use "... 3< file ..." on the command line, use "r" as the type
on fdopen.
... the shell allows only single-digit fd's ...
From keesan@bbncca:
------------------
Simply do I/O to the desired file descriptor as if you had opened it within
your program. E.g.
main(){write(3,"Hello, world\n",13);}
If you want to use stdio, then just insert
FILE *fp3;
fp3 = fdopen(3,"w");
into your program and use fwrite or putc to FILE fp3. What is happening
is that when you say:
$ command 3>foo
to the shell, the shell opens file "foo" for writing, with file descriptor 3,
and then executes the command as a child process, which inherits all of the
open files belonging to its parent (the shell).
From ado@elsie:
--------------
If you're on a Berkeley system, the function call
fdopen(3, "w");
returns a FILE pointer that can be used to write to the file associated with
file descriptor 3; see the manual page on "fopen" in section three of the
Programmer's Manual for details.
If you're not on a Berkeley system, I don't know of a portable way to do
it. Here's a version of "fdopen" that might work on most systems, though:
#include
FILE * fdopen(fildes, type)
char * type;
{
register FILE * fp;
fp = fopen("/dev/null", type);
if (fp == NULL)
return NULL;
close(fp->_file);
fp->_file = fildes;
return fp;
}
From dpg@busch:
--------------
file descriptors are preserved across forks and execs, so all you need to
insure is that the descriptor for your file has a specific value. The dup2(2)
call does this, so
int fd, pid
if ((fd=open("myfile", mode)) < 0)
terminate();
switch (pid=fork()) {
case -1:
terminate();
case 0: /* child */
dup2(fd, 3)
exec(program, ...);
terminate(); /* couldn't exec */
default: /* parent */
break;
}
For calling f77, see the f77 example.
See also:
ld, (the link editor)
lint, (an enhanced source checker)
make, (C program load library update facility)
cb, (C beautifier reformats C programs)
dbx, (preferred general-purpose debugger)
adb, (another debugger)
rcs, (a source revision control system)
install, (an application installation utility)
See (on 4.x bsd systems) /usr/guest/sam/tests/*.c
for example programs from Sam Leffler exemplifying 4.2 programs which
use signals, pipes, and IPC (including Datagrams, TCP, pup, and raw).