Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

This chapter is from the book

10.3 Process Information

The kernel makes available quite a bit of information about each process, and some information is passed to new programs when they are loaded. All of this information forms the execution environment for a process.

10.3.1 Program Arguments

There are two types of values passed to new programs when they are run: command-line arguments and environment variables. Various conventions have been set for their usage, but the system itself does not enforce any of these conventions. It is a good idea to stay within the conventions, however, to help your program fit into the Unix world.

Command-line arguments are a set of strings passed to the program. Usually, these are the text typed after the command name in a shell (hence the name), with optional arguments beginning with a dash (-)character.

Environment variables are a set of name/value pairs. Each pair is represented as a single string of the form NAME=VALUE, and the set of these strings makes up the program's environment. For example, the current user's home directory is normally contained in the HOME environment variable, so programs Joe runs often have HOME=/home/joe in their environment.

Both the command-line arguments and environment are made available to a program at startup. The command-line arguments are passed as parameters to the program's main() function, whereas a pointer to the environment is stored in the environ global variable, which is defined in <unistd.h>. [3]

Here is the complete prototype of main() in the Linux, Unix, and ANSI/ISO C world:

int main(int argc, char * argv[]);

You may be surprised to see that main() returns a value (other than void). The value main() returns is given to the process's parent after the process has exited. By convention, 0 indicates that the process completed successfully, and non-0 values indicate failure. Only the lower eight bits of a process's exit code are considered significant. The negative values between -1 and -128 are reserved for processes that are terminated abnormally by another process or by the kernel. An exit code of 0 indicates successful completion, and exit codes between 1 and 127 indicate the program exited because of an error.

The first parameter, argc, contains the number of command-line arguments passed to the program, whereas argv is an array of pointers to the argument strings. The first item in the array is argv[0], which contains the name of the program being invoked (although not necessarily the complete path to the program). The next-to-last item in the array argv[argc - 1] points to the final command-line argument, and argv[argc] contains NULL.

To access the environment directly, use the following global variable:

extern char * environ[];

This provides environ as an array of pointers to each element in the program's environment (remember, each element is a NAME=VALUE pair), and the final item in the array is NULL. This declaration appears in <unistd.h>, so you do not need to declare it yourself. The most common way of checking for elements in the environment is through getenv, which eliminates the need for directly accessing environ.

const char * getenv(const char * name);

The sole parameter to getenv() is the name of the environment variable whose value you are interested in. If the variable exists, getenv() returns a pointer to its value. If the variable does not exist in the current environment (the environment pointed to by environ), it returns NULL.

Linux provides two ways of adding strings to the program's environment, setenv() and putenv(). POSIX defines only putenv(), making it the more portable of the two.

int putenv(const char * string);

The string passed must be of the form NAME=VALUE .putenv() adds a variable named NAME to the current environment and gives it the value of VALUE . If the environment already contains a variable named NAME , its value is replaced with VALUE .

BSD defines setenv(), which Linux also provides, a more flexible and easier-to-use method for adding items to the environment.

int setenv(const char * name, const char * value, int overwrite);

Here, the name and the new value of the environment variable to manipulate are passed separately, which is usually easier for a program to do. If overwrite is 0, the environment is not modified if it already contains a variable called name. Otherwise, the variable's value is modified, as in putenv().

Here is a short example of both of these functions. Both calls accomplish exactly the same thing, changing the current PATH environment variable for the running program.

putenv("PATH=/bin:/usr/bin");
setenv("PATH", "/bin:/usr/bin", 1);

10.3.2 Resource Usage

The Linux kernel tracks how many resources each process is using. Although only a few resources are tracked, their measurement can be useful for developers, administrators, and users. Table 10.1 lists the process resources usage currently tracked by the Linux kernel, as of version 2.6.7.

Table 10.1. Process Resources Tracked by Linux

Type

Member

Description

structtimeval

ru_utime

Total time spent executing user mode code. This includes all the time spent running instructions in the application, but not the time the kernel spends fulfilling application requests.

structtimeval

ru_stime

Total time the kernel spent executing requests from the process. This does not include time spent while the process was blocked inside a system call.

long

ru_minflt

The number of minor faults that this process caused. Minor faults are memory accesses that force the processor into kernel mode but do not result in a disk access. These occur when a process tries to write past the end of its stack, forcing the kernel to allocate more stack space before continuing the process, for example.

long

ru_majflt

The number of major faults that this process caused. Major faults are memory accesses that force the kernel to access the disk before the program can continue to run. One common cause of major faults is a process accessing a part of its executable memory that has not yet been loaded into RAM from the disk or has been swapped out at some point.

long

ru_nswap

The number of memory pages that have been paged in from disk due to memory accesses from the process.

A process may examine the resource usage of itself, the accumulated usages of all its children, or the sum of the two. The getrusage() system call returns a struct rusage (which is defined in <sys/resource.h>) that contains the current resources used.

int getrusage(int who, struct rusage * usage);

The first parameter, who, tells which of the three available resource counts should be returned. RUSAGE_SELF returns the usage for the current process, RUSAGE_CHILDREN returns the total usage for all of the current process's children, and RUSAGE_BOTH yields the total resources used by this process and all its children. The second parameter to getrusage() is a pointer to a struct rusage, which gets filled in with the appropriate resource utilizations. Although struct rusage contains quite a few members (the list is derived from BSD), most of those members are not yet used by Linux. Here is the complete definition of struct rusage. Table 10.1 describes the members currently used by Linux.

#include <sys/resource.h>
struct rusage
{
  struct timeval ru_utime;
  struct timeval ru_stime;
  long int ru_maxrss;
  long int ru_ixrss;
  long int ru_idrss;
  long int ru_isrss;
  long int ru_minflt;
  long int ru_majflt;
  long int ru_nswap;
  long int ru_inblock;
  long int ru_oublock;
  long int ru_msgsnd;
  long int ru_msgrcv;
  long int ru_nsignals;
  long int ru_nvcsw;
  long int ru_nivcsw;
};

10.3.3 Establishing Usage Limits

To help prevent runaway processes from destroying a system's performance, Unix keeps track of many of the resources a process can use and allows the system administrator and the users themselves to place limits on the resources a process may consume.

There are two classes of limits available: hard limits and soft limits. Hard limits may be lowered by any process but may be raised only by the super user. Hard limits are usually set to RLIM_INFINITY on system startup, which means no limit is enforced. The only exception to this is RLIMIT_CORE (the maximum size of a core dump), which Linux initializes to 0 to prevent unexpected core dumps. Many distributions reset this limit on startup, however, as most technical users expect core dumps under some conditions (see page 130 for information on what a core dump is). Soft limits are the limits that the kernel actually enforces. Any process may set the soft limit for a resource to any value less than or equal to that process's hard limit for the resource.

The various limits that may be set are listed in Table 10.2 and are defined in <sys/resource.h>. The getrlimit() and setrlimit() system calls get and set the limit for a single resource.

Table 10.2. Resource Limits

Value

Limit

RLIMIT_AS

Maximum amount of memory available to the process. This includes memory used for the stack, global variables, and dynamically allocated memory.

RLIMIT_CORE

Maximum size of a core file generated by the kernel (if the core file would be too large, none is created).

RLIMIT_CPU

Total CPU time used (in seconds). For more information on this limit, see the description of SIGXCPU on page 221

RLIMIT_DATA

Maximum size of data memory (in bytes). This doesn't include memory dynamically allocated by the program.

RLIMIT_FSIZE

Maximum size for an open file (checked on writes). For more information on this limit, see the description of SIGXFSZ on page 221.

RLIMIT_MEMLOCK

Maximum amount of memory that may be locked with mlock() (mlock() is decsribed on page 275).

RLIMIT_NOFILE

Maximum number of open files.

RLIMIT_NPROC

Maximum number of child processes the process may spawn. This limits only how many children the process may have at one time. It does not limit how many descendants it may have—each child may have up to RLIMIT_NPROC children of its own.

RLIMIT_RSS

Maximum amount of RAM used at any time (any memory usage exceeding this causes paging). This is known as a process's resident set size.

RLIMIT_STACK

Maximum size of stack memory (in bytes), including all local variables.

int getrlimit(int resource, struct rlimit *rlim);
int setrlimit(int resource, const struct rlimit *rlim);

Both of these functions use struct rlimit, which is defined as follows:

#include <sys/resource.h>

struct rlimit {
  long int rlim_cur;              /* the soft limit */
  long int rlim_max;              /* the hard limit */
};

The second member, rlim_max, indicates the hard limit for the limit indicated by the resource parameter, and rlim_cur contains the soft limit. These are the same sets of limits manipulated by the ulimit and limit commands, one or the other of which is built into most shells.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020