Unix Unit4 Part A
Unix Unit4 Part A
Process Environment
7.1 Introduction
Before looking at the process control primitives in the next chapter, we need to
the environment of a single process. In this chapter, we'll see how the examine
main
called when the program is executed, how command-line arguments are passed function is
to the
new program, what the typical memory layout looks like, how to allocate additional
memory, how the process can use environment variables, and various ways for the
process to terminate. Additionally, we'll look at the longjmp and setjmp functions
and their interaction with the stack. We finish the chapter by
limits of a examining the resource
process.
197
POSIX.1. specified
by _exit
is
13 C,
w
IS0 specifed
by are Exit and exit that headersis different the for reason The
status exit the print $?
echo $
world hello, Section
8.5. process,
interminating the parent
of the and
./[Link] $ chilae the processes,
as
such other functions
on three these effect
of discuss
helloc . gcc $ the We'l
returns: function main the that time status); (int exit VOid
at register
thecontents of
and stack the contents thdepending
e on exit
codes, different
random. <unistd.
h> #include
get likely
to we different
are systems, program
on same compile
the we If
in the run and compile we When status); Exit(int void
iscode exit the that see we7.1,Figure program
status);exit(int void
program ClassicC Figure
7.1 <stdlib.
h> #include
kernel. the returns
to
world\n") ; "hello, print£ ( processing
tha and cleanup certain performs which exit, immediately,
and kernel
return
teto which _Exit,normally:_exit
and program terminatea functions Three
main()
Functions Exit
<stdio.
h> #include
example. world" "hello, classic 7.1
the isFigure program
in The argv))? (argC, (main exit
Example ike look could main callanguage)
to l the assembly coded
in often C(it
is coded
in
the called.
If function
is exit returns,
the function main the
thatroutine
i wrso itstart-up
en mentioned thatroutine start-up
we The
is previous
also section the in
furnction. main the from 12. andChapters1l threads
in
threads
until
dwe three the ignore we'l now, For
return(0); specific
to methodstermination
is requestcancellation thread
ato last thResponse
e of 8.
same the 11.5
>and13(Sections
aS aof
signal Receipt 7.
exit(0);
10.(Section
2)
10.1(Section
7) abort Calling 6.
same the with
Thus value.
Returning Abnormal
to function
is main the from value integer an ways: three termination
occurs
in
exít calling equivalent
exitpthread Calling 5.
function exit the a or
tocall statement thread last the from 11.5(Section
)
return explicit without
an reached function
was main the ofend thundefined
e if was
start ifromts thread of
last the Return 4.
standard. of
0 the version
ISC 1999 is
the with new behavior This 11.5)(Section routine
status the
exitHistorically, and or_Exit _exit Calling 3.
main
process
0. is the statusof exit return), the implicit (an end" the off1"falls status exit exit Calling 2.
type return thHowever,
e if undefined. process of
the without
integer anmain is of is
integet returrn
an declared to notfunction
is main the (c) value, main from Return 1.
the
or return ofany a (a) If
(b)
status, exit without
an functions is these status.
return does
| aastatus
of main exit examine the to way provideacalled shells System UNIX Most All i ways:
process. argument, integer single functions exit three Section eight
which
we
expect
a 5.5 termination Normal terminate. process
to afor ways are There
exit the call to flushed betodataoutput buffered causes
all this I/Othatstandard
file). the (written library: Termination Process
open al called function fclose theHistorically, 7.3
from Recall streans. clean performeda for always is function
theshutdown
of has exit the
Soction
73
Environment Process
Termínation Process 198
199
7.2). Figure shown
in (not signal terminated registered. was ittimes
as many called
as function
is registration.
Each
arily bealso proces
can exit),A calling implicitly
(by explicitly
or aby ner theu order
of reverse functions
in these calls function exit The value. returna
alled, is
Exit _exit
or terminate
if isvoluntarily canprocess
waay only The alled. expectedto not isarguments
and any passed not is
called,
it function this When
nctionsis exec the of
one ifkernel
is the executed
by be
program
can waay only lne atexit. argument
to thefunction
as address
aof the pass we
that declaration
says This
error nonzero
on OK, Returns:
if 0
terminates howit andstarted program
is HowaC [Link]
2 (void);) (*func) (void atexit int
<stdlib.h> #include
function. atexit tcalling
he registered
by are handlers
and exit called arThese
e exit.
kernel automatically
calledby are functions
that 32
least register
at cprocess
an aC,
1SO With
Function atexit
status. exit its fetch then complete,
and process
to the for
exec executed,
wait program
be to causea canprocess any how se well chapter, next the In
used. are
routine warning
onadditional unless warnings compiler extraneous these enmit doesn't usually
Exit start-up C com. GNUC the that Notwarrings.
e their verbosity
of the in
varycompilers Different
cleanup or returm) not
(does
I/standard
0 erim exit POSDX.1.
exit
c": ISo both specified
by definition the isthat since integer, returning
an as
main show
ter this integer.
In signed supposed
a beto main
is type
of return the sincewarnings,
process user I
function return) not(does
function othergenerate can and programming
text), (especially
ain right look doesn't
rerum main
Exit, retur ingbut Duñ compiler the ofrid gets This exit. calling continue and int, instead
of void,
exit exit
handler exit
call
environ: HOME=/home/sar\o appearingoutside any function causes this variable to be stored lin the initialized
withits initial value.
PATH=: /bin:/usr/bin datasegment
Uninitialized data segment, often called the bss
SHELL=/bin/bash\n segment,
ancient assembler operator that stood for "block started by symbol." Data an
named after in
+USER=sar\0
segmentis initialized by the kernel to arithmetic 0 or null before the
LOGNAME=sar\0 this
program starts executing. The Cdeclaration pointers
NULL
long sum[ 1000]:
appearing outside any function causes this variable to be stored in the
Figure 7.5 Environment consisting of five C character strings ninitialized data segment.
Stack, where automatic variables are stored, along with information that is saved
environment list, and each time a function is called. Each time a function is called, the address of
environment pointer, the array of pointers the the strings they where to return to and certain information about the caller's environment, such
to the environment strings.
By convention, the environment consists of Weme of the machine registers, are saved on the stack. The newly called
function then allocates room on the stack for its automatic and temporary
name=value variables. This is how recursive furnctions in Ccan work. Each time a recursive
names are entirely function calls itself, a new stack frame is used, so one set of variables doesn't
strings, as shown in Figure 7.5. Most predefined uppercase, but this interfere with the variables from another instance of the function.
is only a convention.
Historically, most UNIX systems have provided a third argument to the main Heap, where dynamic memory allocation usually takes place. Historically, the
function that is the address of the environment list: heap has been located between the uninitialized data and the stack.
int main ( int argc, char *argv[], char *envp U):
Eeure 7.6 showslooks;
the typical arrangement of these segments. This is alogical picture of
Because ISO Cspecifies that the main function be written with two arguments, how a program there no requirement that a given implementation arrange its
is
because this third argument provides no benefit over the global variable e memoryinthis fashion. Nevertheless, this gives us a typical arrangement to describe.
POSIX.1 specifies that environ should be used instead of the (possible) th Wh Linux on a 32-bit Intel X86 processor, the text segment starts at location
argument. Access to specific environment variables is normally through the gete nw08048000, and the bottom of the stack starts just below 0xC0000000. (The stack
and putenv functions, described in Section 7.9, instead of through the enviv ornws from higher-numbered addresses to lower-numbered addresses on this particular
variable. But togo through the entire environment, the environ pointer must be se architecture.) The unused virtual address space between the top of the heap and the top
of the stack is large.
7.6 Memory Layout of a C Program Several more segment types exist in an [Link], containing the symbol table, debugging
information, linkage tables for dynamic shared libraries, and the like. These additional
Historically, a Cprogram has been composed of the following pieces: sections don't get loaded as part of the program's image executed by a process.
Text segment, consisting of the machine instructions that the CPU executs Note from Figure 7.6 that the contents of the uninitialized data segment are not
Usually, the text segment is sharable so that only a single copy needs to be n stored in the program file on disk, because the kernel sets the contents to 0 before the
memory for frequently executed programs,such as text editors, the Ccompilet program starts runing. The only portions of the program that need to be saved in the
the shells, and so on. Also, the text segment is often read-only, to prevent a program file are the text segment and the initialized data.
program from accidentally modifying its instructions.
206 Memory Allocation 207
Process Environment
o r t oZ
n 8
Figure 7.6 Typical memory arrangement 18 specifiesthree functions for memory allocation:
1SOC
malloc, which allocates a specified number of bytes of memory. The initial
The size(1) command reports the sizes (in bytes) of the text. 1.
value of the memory is indeterminate.
segments. For example: data, and bs calloc, which allocates space for a specified number of objects of a specified
2. 0 bits
size. The space is initialized to all
$ size /usr/bin/cc /bin/sh
text data bss dec hex filename
346919 3576 6680 357175 57337 /usr/bin/cc realloc, which increases or decreases the size of a previously allocated area.
3.
102134 1776 11272 115182 lclee /bin/sh When the size increases, it may involve moving the previously allocated area
The fourth and fifth columns are the total of the three sizes, displayed in decimal.. somewhere else, to provide the additional room at the end. Also, when the size
increases, the initial value of the space between the old contents and the end of
hexadecimal, respectively. indeterminate.
the new area is
#include <stdlib.h>
7.7 Shared Libraries
void *malloc ( size_t size) ;
Most UNIX systems today support shared libraries. Arnold (1986] describes an earl
implementation under System V, and Gingell et al. [1987] describe a difere void *calloc (size_t nobj, sizet size);
implementation under SunOS. Shared libraries remove the common library routins void *realloc (void *ptr, sizet newsize ) ;
from the executable file, instead maintaining a single copy of the library routing Allthree return: non-null pointer if OK, NULL On error
somewhere in memory that all processes reference. This reduces the size of each
executable file but may add some runtime overhead, either when the program is first void free (void *ptr);
executed or the first time each shared library function is called. Another advantage of
shared libraries is that library functions can be replaced with new versions without The pointer returned by the three allocation functions is guaranteed to be suitably
having to relink edit every program that uses the library (assuming that the number and aligned so that it can be used for any data object. For example, if the most restrictive
type of arguments haven't changed). alignment requiremnent on a particular system requires that doubles must start at
Different systems provide different ways for a program to say that it wants to use or memory locations that are multiples of 8, then all pointers returned by these three
not use the shared libraries. Options for the cc(1) and ld(1) commands are typical. As functions would be so aligned.
Process Environment
objects can be unrelated to the code corrupting them, making it even
These source of the
Because the three alloc functions return a generic void
difficultto find the
objects.
errors that can be fatal are corruption.
possible freeing a block that was already freed and
#include <stdlib.h> (to obtain the function prototypes),
to cast the Ponter returned by these functions when we assign it to a
different type. The default noturn value for undeclared functhons is int.
we do
not peoxiplntri,tly more
Other
functions.
with a pointer that was not obtained from one of
free
calling If a process calls malloc but forgets to call £ree, its
continuallyincrease:his is called leakage. If we do not call
the three alloc
memory usage w
hide an error on systems
free to return unused
process's,address space will slowly increase until
without the Proper function declaration could return thesizeof aperformance no free space is lert.
thiswhere ase)he s
of type int differs from the size of afunction's value (a pointer in can degrade from excess
ptr to be deallocat
space,
this time, paging overhead.
The free causes the space pointed to byand
function can be allocat
During memory allocation errors are difficult to track down, some
systems provide
space is usually put intoa pool of available memory
to one of the three alloc functions.
Tahliaster fre a
in
Because
of
these hunctions that do additional error checking every time one of the three
functions or free is called. These versions of the functions are often specifhea
versions
change the size of a previously
Ihe realloc function Jets us area's size.) For example, if wo allocated area. alloc,
including a
special library for the link editor. There are also
compile with special flags to publicly available
most common usage is to increase
realloc. If
an
we fill in at runtime but later
find
Dl2 elenments in an arrav that there is room beyond the end of that thel existing
alweocateneedrOOm(h hy
SOurces that youcan enable additional runtime checking-
FreeBSD, Mac OS X. and Linux support additional debugging through the setting of
room, we can call additional
simply allocates this
then realloc area at regon o n
environment variables. In addition, options can be passed to the FreeBSD library through the
the requested
returns the space,
same pointer that we passed it. But if there isn't room,
512-elemernt.
realloc ihe end and asrmbolic link /etc/malloc. con f
copies the existing array to the
another area that is large enough, Because
the pointer to the new area.
frees the old area, and returns into this area. Exercise 4.16 and
the area ma new area AlternateMemory. Allocators
we shouldn't have any
pointers
handle a pathname of any
Figure
length.
Figure C3mayShowmoehe replacements for malloc and free are available. Some systems already include
use of realloc with getcwd to arrays
an example that uses realloc to avoidrealloc
with fixed, compile-time
size of
c'
1721 Showe Many providing alternative memory allocator implementations. Other systems
Note that the final argument to
the new
special case, if ptr is a
the reginulon, not th
libraries
provide onlythe standard allocator, leaving it up to software developers to download
difference between the old and new sizes. As a alternatives,:if desired.
We discuss some of the alternatives here.
realloc behaves like malloc and allocates a region of the specified newsize pointe,
we
Older versions of these routines allowed us to realloc a block that had
last call to malloc, real loc, or calloc. This trick dates
back to
Version 7and freed since te Jibmalloc
search strategy of malloc to perform storage compaction. Solaris still supports exploited ta SVR4-based systems, such as Solaris, include the libmalloc library, which provides a
but many other platforms do not. This feature is deprecated and should not be iuedthis featue interfaces matching the ISO C memory allocation functions. The libmalloc
set of
mallopt, afunction that allows a process to set certain variables that
libraryincludes
operation of the storage allocator. Afunction called mallinfo is also
The allocation routines are usually implemented with the sbrk(2) system call n. control the
system call expands (or contracts) the heap of the process. (Refer to Figure 76 statistics on the memory allocato.
available to provide
sample implementation of malloc and free is given in Section 8.7 of
Ritchie [1988). Kernighan and
Although sbrk can expand or contract the memory of a process, most versions of PMalloc
malloc and free never decrease their memory size. The space that we fre t. fno961 describes a memory allocator that allows processes to allocate memory using
available for a later allocation, but the freed space is not usually returned to the kemel Aifferent techniques for different regions of memory. In addition to the functions
instead, that space is kept in the malloc pool. snecificto vmalloc, the library provides emulations of the ISO C memory allocation
Most implementations allocate more space than requested and use the additional functions.
space for record keeping-thesize of the block, a pointer to the next allocated blok.
and the like. As a consequence, writing past the end or before the start of an allocated quick-fit
area could overwrite this record-keeping information in another block. These types of
errors are often catastrophic, but difficult to find, because the error may not show up Historically, the standard malloc algorithm used either a best-fit or a first-fit memory
untilmuch later. allocation strategy. Quick-fit is faster than either, but tends to use more memory.
Writing past the end or before the beginning of a dynamically allocated buffer can Weinstock and Wulf (1988) describe the algorithm, which isbuffers
based on
on different
splitting free
up
corrupt more than internal record-keeping information. The memory before and after a memory into buffers of various sizes and maintaining unused
dynamically allocated buffer can potentially be used for other dynamically allocated lists, depending on the buffer sizes. Most modern allocators are based on quick-fit.
Environment Variables 211
210
Process Environment o nZ
The alloca function increases the size of the stack frame. The functioangereturns
disadvant
to increase the size of is that
LCNUMERIC
name of locale for numeric editing
name of locale for date/ time formatting
some systems can't support alloca, if it's impossible many
C TIME terminal height
frame after the function has been called. Nevertheless, the
software packages Usestackit INES
LOGNAME
login narme
and implementations exist for a wide variety of systems. MSGVERB
XSI Emtnsg(3) message components to process
NLSPATH sequence of templates for message catalogs
Alfour platforms discussed in this text provide the alloca function. PATH
list of path prefixes to search for executable file
absolute pathname of current working directory
|PWD name of user's preferred shell
SHELL
7.9 Environment Variables TERM
terminal type
TMPDIR pathname of directory for creating temporary files
As we mentioned earlier, the environment strings are usually of the form time zone information
name=value
Figure 7.7 Environment variables defined in the Single UNIX Specification
The UNIX kernel never looks at these strings; their interpretation is up to the vatio.
applications. The shells, for example, use numerous environment variables. Soma
such as HOME and USER, are set automatically at login; others are left for us to set. N In addition to fetching the value of an environment variable, sometimes we may
normally set environment variables in a shell start-up fle to control the shell's actions want to set an environment variable. We may want to change the value of an existing
If we set the environment variable MAILPATH, for example, it tells the Bourne shel variable or add a new variable to the environment. (In the next chapter, we'l see that
GNU Bourne-again shell, and Korn shell where to look for mail. we can affect the environment of only the current process and any child processes that
ISO C defines a function that we can use to fetch values from the environment, but
this standard says that the contents of the environment are implementation defined. we invoke. We cannot affect the environment of the parent process, which is often a
#include <stdlib.h>
shell. Nevertheless, it is still useful to be able to modify the environment list.)
Unfortunately, not allsystems support this capability. Figure 78 shows the functions
char *getenv(const char *name); that are supported by the various standards and implementations.
Returns: pointer to value associated with name, NULL if not found
212
Process Environment
G t oZ
n In
8etjmp and longimp Functions 213
#include "apue.h"
(hapt
bottom of stack
|higheraddress
#define TOK ADD 5
stack frame
Void for main
do_ line(char *);
void cmd add(void);
int get token (void); stack frame
int for do line
msetp. )mTp,helongisandecond
from set s
value higher address
Second, val, is a nonzem value that becomes the return
dgumernt allows us to use more than one longjmp tor each setjmp, cjFor stack frame
of 1and also call longjmo fr
could longjmp from cmd add with a valreturn
for main
printf ("in £1() :\n") ; Well returm to these two functions,setjmp and longjmp, in Chapter 10when we
printf("globval = %d, autoval = td, regival = td, " kouss signal handlers and their signal versions: sigset jmp and siglongjmp.
volaval = td, statval = $d\n", globval, i, j, k, l);
f2();
Varlables
Potentlal Problem with Automatic
static void
f2 (void) Having looked at the way stack frames are usually handled, it is worth looking at a
potential error in dealing with automatic variables. The basic rule is that an automatic
longjmp(jmpbuffer, 1); variable can never be referenced after the function that declared it returns. Numerous
warnings about this can be found throughout the UNIX System manuals.
Figure 7.14 shows a function called open data that opens a standard I/0 stream
Figure 7.13 Effect of longjmp on various types of variables
and sets the buffering for the stream.
220
Process Environment getrlimit and setrlimit Functions 221
1f
(( tp = fopen( " datafile", "r"))
return (NULL);
(setvbuf(fp, databuf, IOLBF,
= NULL)
BUFSIZ) = 0)
buf er An
The
which
resOurce
limits
implementation.
takes on one of the following
are defined by the values. Figure 7.15 shows
Single UNDX Specification and supported by each
return (NULL);
/* error */ The maximum size in bytes of a process's total
return(fp);
memory. This affects the sbrk function (Section 1.11)available
RLIMITAS
and the
Figure 7.14 Incorrect usage of an automatic variable mmap function (Section 14.8).
RLIMITCORE The maximum size in bytes of a core file. A limit of 0
the creation of a core file. prevents
The problem is that whern open data returns, the space it used on the
standardstack
used by the stack frame for the next function that is called. But the wil RLIMITCPU The maximum amount of CPU time in seconds. When the
will still be using that portion of memory for its stream buffer. Chaos is
To correct this problem, the array databuf needs to be allocatedfrom globalsure
either statically (staticor extern) or dynamically (one of the alloc functioe
to
I/Ofbmeramryory, RLIMIT_DATA
soft limit is exceeded, the SIGKCPU signal is sent to the
process.
The maximum size in bytes of the data segment: the sum of
the initialized data, uninitialized data, and heap from
7.11 getrlimit and setrlimit Functions Figure 7.6.
RLIMIT FSIZE The maximum size in bytes of a fle that may be created.
Every process has a set of resource limits, some of which can be queried andi When the soft limit is exceeded, the process is sent the
the getrlimit and setrlimit functions. changed by SIGXFSz signal.
#include <sys/resource.h> RIIMIT_ MEMLOCK The maximum amount of memory in bytes that a process can
lock into memory using mlock(2).
int getrlimit(int resource, struct rlimit *rlptr);
RLIMIT MSGQUEUE The maximum amount of memory in bytes that a process can
int setrlimit(int esource, const struct rlimit *rlptr): allocate for POSIX message queues.
Both return: 0if OK, -l on error RLIMIT NICE The limit to which a process's nice value (Section 8.16) can be
raised to affect its scheduling priority.
These two functions are defined the XSI option in the Single UNIX Specification. The RLIMIT NOFILE The maximum number of open files per process. Changing
resource limits for a process are normally established by process 0 when the system i this limit affects the value returned by the sysconf function
initialized and then inherited by each successive process. Each implementation has its ou for its _sC _OPEN MAX argument (Section 2.5.4). See
way of tuning the various limits.
Figure 2.17 also.
Each call to these two functions specifies asingle resource and a pointer to the RLIMIT NPROC The maximum number of child processes per real user ID.
following structure: Changing this limit affects the value returned for
struct rlimit { SC CHILD MAX by the sysconf function (Section 2.5.4).
rlim t rlim cur; /* soft limit: current limit *} RLIMIT NPTS The maximum number of pseudo terminals (Chapter 19) that
rlim t rlin max; /* hard limit: maximum value for rlim cur */ a user can have open at one time.
222 Process Environment getrlimit and setrlimit Functions 223
inplermentatios,we have
conditionally included the resource names that differ. Note
RLIMIT RSS systems define rlim _t to be an
Maximum resident set size (RSS) in unsígned long long
loong. This definition can even change on the same system, instead
of an
physical memory is low, the kernel bytes. some
depending
processes that exceed their RSS. akes unslgned
whether we compile the program to support 64-bit files. Some limits apply to file size,on
that
RLIMIT STACK The maximum size in bytes of the stack, See funchn #define doit(name pr limits (#name, name)
#1fdef RIIMIT AS
FreeBSD Linux Mac OS X doit(RLIMIT_AS);
Limit XSI 8.0 3.2.0 10.6.8 Solaris
10 #endif
RLIMIT AS doit (RLIMIT CORE):
RLIMIT CORE doit(RIIMIT CPU):
RLIMIT CPU doit (RLIMIT DATA):
RLIMIT_ DATA doit(RIIMIT_FSIZE):
RLIMIT FSIZE
RLIMIT MEMLOCK RIIMIT MEMLOCK
RLIMIT MSGQUEUE #ifdef
doit (RLIMIT MEMLOCK):
RLIMIT NICE
RLIMIT NOFILE #endif
RLIMIT NPROC 41fdef RLIMIT MSGQUEUE
RLIMIT NPTS
RLIMIT_RSS doit (RILIMIT_ MSsGQUEUE );
RLIMIT SBSIZE #endif
RLIMIT SIGPENDING #ifdef RLIMIT NICE
RLIMIT STACK
RLIMIT SWAP doit (RLIMIT NICE) ;
RLIMIT VMEM #endif