Linux Programming--linux Environment (fourth chapter)

Source: Internet
Author: User
Tags local time time and date

Linux environment this article for Linux environment, code in Linux Environment code download. When the when you write a program in Linux, consideration must be given to The program will run in a multi-tasking environment。 This means that there will be multiple programs running at the same time, and they share machine resources such as memory, disk space, and CPU cycles. Even the same program will have multiple instances running concurrently. Most importantly, these programs can be independent of each other, be able to understand their environment, and be able to operate correctly without creating conflicts.
This chapter describes the environment in which the program runs, how the program obtains information about its operating conditions through the environment, and how the user can change the behavior of the program.
4.1 Program parameters when a Linux program written in C is run, it starts with the main function, and for these programs the declaration of the main function is as follows:
int main (int argc, char *argv[])
which ARGC is the number of program parameters, argv is an array of strings representing the parameters themselves
It can also be simply declared as:
Main ()
Because the default return value type is int, and a formal parameter that is not used in a function does not need to be declared. ARGC and argv are still there, but they cannot be used if they are not declared.
Regardless of when the operating system starts a new program, the parameters argc and argv are set and passed to main, which is usually provided by another program, which is typically the shell, which requires the operating system to start the new program. The shell accepts the command line entered by the user, breaks the command line into words, and then puts the words into the argv array.
For example, if we enter the following command for the shell:
Myprog left right ' and center '
The program prog will start with the main function, with the parameters of the main band:
Argc:4
argv:{"Myprog", "left", "right", "and Center"}
Attention The number of arguments includes the program name itself, the argv array contains the program name, and it acts as the first element argv[0]。 Because the shell command uses quotation marks, the fourth argument is a string that contains a space.
Command-line arguments are useful for passing information to a program. For example, we can use command-line arguments in a database application to pass the name of the database you want, so that you can use the same program on multiple databases. Many utility programs also use command-line parameters to change the behavior of the program or to set options. These so-called commands or switches can usually be set using a dash-line argument at the beginning. For example, the sort program can use a switch to reverse order:
Sort-r file
Write the program argc.c to check the parameters.
4.1.1 Getoptlinux provides the getopt function, which supports options that require correlation values and do not require associated values.
#include <unistd.h>
int getopt (int argc, char *const argv[], const char *optstring);
extern char *optarg;
extern int Optind, opterr, optopt;
The getopt function passes the ARGC and argv of the main function of the program as arguments, and accepts an option to specify the string optstring, which tells Getopt which options are available and whether they have associated values. Optstring has only one character list, and each character represents a single-symbol option. If a character is followed by a colon:, it indicates that the option has an associated value as the next parameter.
For example, we can use the following call to handle the above example:
Getopt (argc, argv, "IF:LR");
It allows a few simple options:-i,-l,-r and-F, where the-f option is followed by a filename parameter. Using the same parameters, but invoking the command in a different order will change the behavior of the program.
The return value of getopt is the next option character in the argv array.
Getopt has the following behavior:
If the option has an associated value, the external variable optarg points to the value.
If the option finishes processing, GETOPT returns-1, special parameters-will make the getopt stop scanning option.
If an unrecognized option is encountered, GETOPT returns a question mark and saves it to the external variable optopt.
If an option requires an associated value, but the user does not provide this value, getopt usually returns a question mark.
Writing a program argopt.c
The 4.1.2 Getopt_longgnu C function contains another version of Getopt, called Getopt_long, which accepts long arguments that begin with a double dash.
You can use Getopt_long to create a new version of the sample program that can use the long parameter options that are equivalent to the preceding options:
./longopt--initialize--list ' Hi there '--file fred.c-q
Writing a program longopt.c
4.2 Environment variable environment variables are variables used to control shell scripts and other program behavior, which can be used to configure the user environment. For example, each user has an environment variable home, which defines the user's home directory, which is the default starting location for that user's session.
Echo $HOME
The UNIX specification defines a number of standard environment variables for various applications, including terminal type, default editor, time zone, and so on. The C language can access environment variables through the putenv and getenv functions:
#include <stdlib.h>
char* getenv (const char* name);
int putenv (const char* string);
The environment consists of a set of strings formatted as "First name = value". The getenv function searches for a string in the environment with the given name and returns the value associated with the renamed name. If the requested variable does not exist, it returns NULL. Because the string returned by getenv is stored in the static space provided by getenv, if you want to use it further, you must copy it to another string, lest it be overwritten by subsequent getenv calls.
The Putenv function takes a string formatted as a "First name = value" As an argument and adds the string to the current environment. If the environment cannot be scaled due to insufficient available memory, it fails and returns-1.
Writing a program ENVIRON.C
Attention: The environment is only valid for the program itself, and changes made in the program are not reflected in the external environment, because the value of the variable is not propagated from the child process (the program) to the parent process (shell)
The use of 4.2.1 environment variables often uses environment variables to change the way they work. The user can set the value of the environment variable by setting it in the default environment, setting it up with a. Profile that is read by the login shell, using the shell-specific startup file (RC), or setting the variable on the shell command line. For example:
./environ.exe Fred
Fred=hello./environ Fred
The shell assigns the variable at the beginning of the line as a temporary change to the environment variable.
The environment of the 4.2.2 Environ variable program consists of a set of strings formatted as "First name = value". The program can access this array of strings directly through the environ variable. The declaration of the Environ variable is as follows:
#include <stdlib.h>
extern char** environ;
4.3 Time and date can usually determine the time and date is very useful for a program. The program may want to record the time it is running, or it may need to change the way it runs at some point.
Time is handled by a predefined type time_t. This is an integer type that is large enough to hold the date and time calculated in seconds.
#include <time.h>
time_t Time (time_t *tloc);
You can call the time function to get the underlying temporal value, which returns the number of seconds since the era began. If Tloc is not a null pointer, the time function also writes the return value to the position pointed to by the Tloc pointer
Writing a program envtime.c
The function difftime is used to calculate the number of seconds between two time_t values and returns it as a double type
#include <time.h>
Double Difftime (time_t time1, time_t time2);
The Difftime function calculates the difference between two time values and returns the value of Time1-time2 as a floating-point number.
The Gmtime function decomposes the underlying time value into a structure that contains some commonly used members:
#include <time.h>
struct TM *gmtime (const time_t timeval);
If you want to see local time, you need to use the LocalTime function.
#include <time.h>
struct TM *localtime (const time_t *timeval);
The LocalTime function, like Gmtime, is adjusted in addition to the values contained in the structure it returns, based on the local time zone and whether daylight savings is used.
To get a more "friendly" time and date representation, like the output of the date command, you can use the Asctime function and the CTime function:
#include <time.h>
Char *asctime (const struct TM *timeptr);
Char *ctime (const time_t *timeval);
The Asctime function returns a String that represents the time and date given by the TM structure Timeptr. The returned string has a format similar to the following:
Mon June 8 16:23:05 2015
4.4 Temporary files In many cases, the program takes advantage of temporary storage methods in the form of files. These temporary files may hold a computed intermediate result, or it may be a backup of the file before the critical operation.
The disadvantage of temporary files is that you must ensure that the file name selected by your application for temporary files is unique.
Use the Tmpnam function to generate a unique file name.
#include <stdio.h>
Char *tmpnam (char *s);
If you encounter a situation where you need to use a temporary file immediately, you can use the Tmpfile function to open it while naming it.
#include <stdio.h>
file* tmpfile (void);
The Tmpfile function returns a file stream pointer that points to a unique temporary file. The file is opened in read-write mode and is automatically deleted when all references to it are closed.

Linux Programming--linux Environment (fourth chapter)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.