UNIX advanced environment programming

Source: Internet
Author: User
Tags flock signal handler superuser permission

[07] UNIX process environment
========================================
1. Process Termination
Atexit () function registration termination processProgram.
Exit () or return statement:
Terminate the Handler-> terminate the Handler-> standard I/O cleanup-> _ exit ()-> enter the kernel.
_ Exit () directly enters the kernel.

2. Environment table
Extern char ** environ;
Example:
For (I = 0; Environ [I]! = NULL; I ++)
{
Printf ("env [% d]: % s \ n", I, Environ [I]);
}

3. C program bucket layout
* The text is the Code segment
* the initialization data segment is shown as follows: int maxcount = 99;
* BSS (non-initialized data) such as long sun [1000];
* Information Required for automatic stack variables and function calls
* stack dynamic access allocation, at the top of the BSS and at the bottom of the stack.
-----------------------------------------------------------
high address stack-> .... <-low address of the initial data body of heap BSS
-----------------------------------------------------
note: Use the size command to view text data BSS information.

4. Memory Allocation
Alloca () is used to allocate space in the stack. After the function call is completed, the space is automatically released, but some systems do not support it.

5. Environment Variables
Char * getenv (char * Name );
Int putenv (const char * Str );
Int setenv (const char * Name, const char * value, int rewrite );
Void unsetenv (const char * Name );
Note: The environ table and strings are stored at the top of the stack. When you call the above function, you may need to move it to the heap.

6. setjmp and longjmp

# include
jmp_buf jmpbuffer;
......
_ @: setjmp (jmpbuffer);
......
call my_function ();
......
my_function () {
longjmp (jmpbuffer, 1);
}< br> Note:
* in the code, call the setjmp function at _ @ and call the my_function function at multiple layers.
call the longjmp (, 1) function in the function and adjust the responsible program.
that is, all stack frames on the upper layer are bypassed and jumped to the stack status where _ @ is located.
* setjmp return value: If it is called directly, 0 is returned; otherwise, the second parameter of longjmp is returned.

7. getrlimit and setrlimit
# include
# include
int getrlimit (INT resource, struct rlimit * rlptr);
int setrlimit (INT resource, const struct rlimit * rlptr);

[08] Process Control
========================================
1. process ID
Process ID:
0 Swapper
1 init, which is called by the kernel after the bootstrap action is completed. It will not terminate, but it is a common user process that runs with the superuser permission.
2-page genie process, pagedaemon
Function:
# Include <sys/types. h>
# Include <unistd. h>
Pid_t getpid (void );
Pid_t getppid (void );
Uid_t getuid (void );
Uid_t geteuid (void );
Gid_t getgid (void );
Git_t getegid (void );

2. Fork Function
Fork (): Creates a sub-process.
# Include <sys/types. h>
# Include <unistd. h>
Pid_t fork (void );

* after fork is called, the child and parent processes continue to execute the code after fork.
* fork returns two times, the child process returns 0, and the parent process returns the child process ID.
* after fork, you cannot know which of the Parent and Child processes are executed first.
example:
int main ()
{< br> If (PDI = fork () <0)
error ();
else if (pid = 0) {// sub-process
}< br> else {// parent process
}< br> ...... // The code after the Parent and Child processes continue to run fork
}< br>
two fork usage
* after fork is executed, the Parent and Child processes execute their own code. Common in network servers.
* different processes run different programs. After fork, the child process calls the exec function.

3. vfork
Vfork () creates a new process.
Difference from fork:
* Vfork ensures that the sub-process is executed before the parent process,
* The vfork sub-process is executed in the address space of the parent process.

4. Wait and waitpid Functions

5. competitive conditions
Multiple processes attempt to process the shared data, but the result depends on the running sequence of the process.

6. Comparison of Six exec Functions
--------------------------------------------------------------
Function path name parameter table argv [] environ envp []
--------------------------------------------------------------
Execl ***
Execlp ***
Execle ***
Execv ***
Execvp ***
Execve ***
--------------------------------------------------------------
P. Take filename as the parameter.
L obtain the parameter table
V indicates removing the argv [] Array
E Indicates taking the envp [] Array

[10] Signal
======================================
1. Concepts
Signal: software interruption, starting with sig, defined in <signal. h>.
Three Signal Processing Methods:
* This signal is ignored, but sigkill and sigstop cannot be ignored because they provide a reliable method for the Super User to terminate or stop the process. If the signal generated by some hardware exceptions is ignored, the process behavior is unknown.
* To capture a signal, notify the kernel to call a user function when a signal occurs.
* Execute the default system action.

2. signal function
# include
void (* signal (INT signo, void (* func) (INT);
note:
* return value void (* signal) (INT);
return the old signal handler pointer.
* parameter
signo: Signal Representation
void (* func) (INT); new signal processing program,
if it is sig_ign-ignore this signal
if it is sig_dfl-default system operation
use the typedef method to define the signal function:
typedef void sigfunc (INT);
sigfunc * signal (INT, sigfunc *);
when a process calls fork, the child process inherits the signal processing method of the parent process. Because the sub-process copies the storage image of the parent process at the beginning, the addresses of all signal capturing functions are meaningful in the sub-process.

3. Kill and raise Functions
# Include <sys/types. h>
# Include <signal. h>

Int kill (pid_t PID, int signo );
Int raise (INT signo );
* Kill sends signals to processes or process groups.
PID> 0: send the signal to the Process
PID = 0 send the signal to the Process Group ID is equal to the Process Group ID of the sending process, and the process has the permission to send signals to all processes.
PID <0 sends the signal to the Process Group ID equal to the absolute value of PID, similar to pid = 0.

* The raise process sends signals to itself.

4. Alarm and pause Functions
Alarm: set a time period. When the time period expires, the sigalrm signal is generated and the process is terminated by default.
# Include <unistd. h>
Unsigned int alarm (unsigned int seconds );
Note:
* Seconds is the number of seconds.
* Each process can only have one alarm time. If the alarm time is set for the process when alarm is called, the residual value of the alarm time is used as the return value of this alarm function call. The previously registered alarm time is replaced by the new value.

# Include <unistd. h>
Int pause (void)
Note:
Pause returns-1 only when a signal processing program is executed and returned from it, and errno is set to eintr.

(There are many alarm examples in the book to illustrate what to pay attention to when using signals)

5. Signal Set
use the sigset_t type to represent a signal set.
# include
int sigemptyset (sigset_t * Set);
int sigfillset (sigset_t * Set);
int sigaddset (sigset_t * Set, int signo );
int sigdelset (sigset_t * Set, int signo);
---- return value: Success 0, error-1
int sigismember (conset sigset_t * set, int signo);
---- return value: True 1, false 0

6. sigprocmask Function
Function: detects or modifies the signal shielding characters of a process.
# Include <signal. h>
Int sigprocmask (INT how, const sigset_t * Set, sigset_t * oset );
Note:
* If the oset is not empty, the oset indicates the current signal shielding character.
* If set is not empty, how indicates how to modify the current signal shielding character.
* How:
* Sig_block or operation
* Sig_unblock and
* Sig_setmask assignment operation

7. sigpending Function
Function: return the blocked signal sets that cannot be delivered and are currently pending.
# Include <signal. h>
Int sigpending (sigset_t * Set );

8. sigaction Function
Function, replacing the signal function.
# Include <signal. h>
Int sigaction (INT signo, const struct sigaction * Act ,\
Struct sigaction * oact );

Struct sigaction {
Void (* sa_handler )();
Sigset_t sa_mask;
Int sa_flags;
};
Sa_handler signal capturing function
The signal shielding word to be added before sa_handler is called by sa_mask. After the call is completed, the signal shielding word of the process is restored to the original value.
Sa_flags signal processing options.

9. sigsetjmp and siglongjmp
# Include <setjmp. h>
Int sigsetjmp (sigjmp_buf ENV, int savemask );
Void siglongjmp (sigjmp_buf ENV, int Val );
Differences:
When the savemask value is not 0, sigsetjmp saves the current blocked word of the process in the Env. When siglongjmp is called, siglongjmp restores the blocked word from it.
However, setjmp and longjmp do not guarantee this operation.

10. sigsuspend Function
# Include <signal. h>
Int sigsuspend (const sigset_t sigmask );

The signal shielding character of a process is set to sigmask. The process is also suspended until a signal is captured or a signal is generated that terminates the process. If a signal is captured and returned from the signal processing program, sigsuspend is returned, and the signal shielding word of the process is set to the value before sigsuspend is called.

[11] Terminals

[12] advanced I/O
==========================================
1. Non-blocking I/O
There are two ways to specify a non-blocking I/O for a given descriptor.
* If you call open to obtain the descriptor, you can specify the o_nonblock flag.
* For opened descriptors, call fcntl to open the o_nonblock File status flag.

2. Record lock
Function: when a process is reading or modifying a part of a file, it can prevent other processes from modifying the same file area. It only locks an area of the file, but also the entire file.
Fcntl record lock
# Include <sys/types. h>
# Include <unistd. h>
# Include <fcntl. h>

Int fcntl (INT filedes, int cmd, struct flock * flockptr );
Parameters:
* CMD/* f_getlk, f_setlk, f_setlkw */
F_getlk if a lock exists, the existing lock information is written to the structure pointed to by flockptr. If it does not exist, set l_type to f_unlck, and save other fields unchanged.
F_setlk: Set the lock described by flockptr. Or, it is used to clear the description Record lock (set l_type to f_unlck ).
F_setlkw this is a version that is blocked by f_setlk.

* Structure pointer below flockptr
Struct flock {
Short l_type;/* f_rdlck, f_wrlck, f_unlck */
Off_t l_start;/* offset in bytes, ralative to l_whence */
Short l_whence;/* seek_set, seek_cur, seek_end */
Off_t l_len;/* length, in bytes; 0 means lock to EOF */
Pid_t l_pid;/* returned with f_getlk */
};

[Note]
1. When the process is terminated and all locks are released, the descriptor locks are also released when the descriptor is closed.
2. After fork, the child process does not inherit the record lock of the parent process
3. After exec, the new program can continue the lock of the original execution Program

[13] genie Process
==================================== ===< br> 1. programming rules
-call fork and then the parent process calls exit.
usage: 1. If the wizard process is started by a shell, the parent process is terminated. The shell determines that the command has been executed successfully.
2. Ensure that the child process is not the first process of a process group, and it processes the ID of the Process Group of the parent process.
-call setsid to create a new session.
1. The process becomes the first process in the dialog period. 2. Become the first process of a new process group. 3. No control terminal.
-change the working directory to the following directory.
-set the blocking word created in the file mode to 0.
1. Remove the blocked characters inherited by the parent process.
-Disable unwanted file descriptors. This is related to specific genie processes.

# Include <sys/type. h>
# Include <sys/STAT. h>
# Include <fcntl. h>
Int daemon_init (void)
{
Pid_t PID;
If (pid = fork () <0)
Return-1;
Else if (PID! = 0)
Exit (0); // parent goes bye-bye
Setsid ();
Chdir ("/");
Umask (0); // clear file mode Creation mask
Return 0;
}

[14] inter-process communication
======================================
1. MPS queue
# Include <unistd. h>
Int pipe (INT filedes [2]);
Filedes [0] is enabled for reading, and filedes [1] is enabled for writing. Output of filedes [1] is the input of filedes [0.

14.6 ----

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.