Special file-proc file system

Source: Internet
Author: User

1. proc file system

The proc file system is a pseudo-file system that only exists in the memory and does not occupy the external storage space. It provides interfaces for accessing system kernel data in the form of a file system. Users and applications can use
Proc obtains the system information and can change some kernel parameters. Because system information, such as processes, is dynamically changed, when a user or application reads the proc file, the proc file system is
Dynamically reads the required information from the system kernel and submits the information.

As a special file, the program can use open, read, write and other functions to manipulate it, and the corresponding information has been obtained.

 

2. Common kernel information

The/proc directory contains two sub-directories, one of which is a sub-directory completely named as a number. This number is the process ID of the relevant process. These directories contain information about running processes.

The remaining subdirectories that do not name numbers are kernel data information. The specific meaning is as follows:

 

Directory Name directory content

APM Advanced Power Management Information

Cmdline kernel command line

Cpuinfo CPU Information

Devices available for devices (Block devices/character devices)

DMA channels used by DMA

File systems supported by filesystems

Interrupts interruption

Ioports I/O port usage

Core impressions of kcore

Kmsg kernel message

Ksyms kernel symbol table

Loadavg Load Balancing

Locks kernel lock

Meminfo memory information

Misc Miscellaneous

List of modules loaded by modules

File System loaded by mounts

Partition tables recognized by the partitions System

RTC real-time clock

Slabinfo slab pool information

Stat comprehensive statistics Status table

SWAps space utilization

Version kernel version

Uptime system normal running time

 

 

In fact, the/proc file system uses
/Files that can be read and written In Proc provide an interactive mechanism for the kernel. Writing these files can change the kernel.
So be careful when modifying these files. The/proc/sys directory stores all files that can be read and written.
Directory, which can be used to change kernel behavior.

/Proc/sys/kernel
-This directory contains information about General kernel behavior.
/Proc/sys/kernel/{domainname, hostname} stores the domain name and Host Name of the machine/network.
These files can be used to modify these names.

$ hostname
machinename.domainname.com

$ cat /proc/sys/kernel/domainname
domainname.com

$ cat /proc/sys/kernel/hostname
machinename

$ echo "new-machinename" > /proc/sys/kernel/hostname

$ hostname
new-machinename.domainname.com

In this way, you can modify the host name by modifying the files in the/proc file system. Many
The files that can be configured exist in/proc/sys/kernel /. It is impossible to list all these files,
You can view more details in this directory.
Another configurable directory is/Proc/sys/Net
. Files in this directory can
Modifies the Network Properties of a machine or network. For example, to modify a file, you can
Addicted to hiding computers.

$ echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all

This will hide your machine in the Network addiction because it does not respond to ICMP_Echo. The host will not respond to it
The Ping query sent by the host.

$ ping machinename.domainname.com
no answer from machinename.domainname.com

To change back to the default setting, as long

$ echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all

There are many others in/proc/sys that can be used to change the kernel attributes.

 

 

3. Read kernel information

 

// Getinfo. c

 

# Include <stdio. h>

# Include <stdlib. h>

# Include <string. h>

# Include <sys/time. h>

# Include <fcntl. h>

# Include <unistd. h>

 

# Deprecision Max 1024

# Define standard 0

# Define short 1

# Define long 2

 

Int get_load_avg ()

{

Char line_buf [Max];

Int FD;

Int N;

Int res =-1;

 

If (FD = open ("/proc/loadavg", o_rdonly) =-1) {// open the proc file with the average load of the Storage System

Perror ("fail to loadavg ");

Exit (-1 );

}

 

If (n = read (FD, line_buf, max) =-1) {// read the average load of the system

Perror ("fail to read ");

Goto err;

}

 

Line_buf [N] = '/0 ';

 

Printf ("average load: % s/n", line_buf );

 

Res = 0;

 

Err:

Close (FD );

 

Return res;

 

 

}

 

/* Search for the required kernel information in the specified proc file and output the information after the found string

* APIs: Path of the specified proc file

* Name: the kernel information to be searched.

*/

Int search (char * path, char * name)

{

Int FD;

Char char_all [Max] = "/0 ";

Char line_buf [Max] = "/0 ";

Char * P;

Char * s;

Int N;

Int res =-1;

 

If (FD = open (path, o_rdonly) =-1) {// open the specified proc file

Perror ("fail to open ");

Exit (1 );

}

 

If (n = read (FD, char_all, max) =-1) {// read the file content into the buffer

Perror ("fail to read ");

Goto err;

}

 

Char_all [N] = '/0 ';

 

P = strstr (char_all, name );

S = strstr (P, "/N"); // This line is the required kernel information

N = s-p + 1;

 

Strncpy (line_buf, P, N );

Printf ("% s/n", line_buf );

 

Res = 0;

 

Err:

Close (FD );

 

Return res;

}

 

Int main (INT argc, char * argv [])

{

Char C1, C2;

Int interval;

Int duration;

Int intervation = 0;

Int reporttype = 0;

Char reptypename [16];

Struct timeval now;

 

Reporttype = standard; // default Standard

Strcpy (reptypename, "standard ");

 

If (argc> 1 ){

Sscanf (argv [1], "% C", & C1, & C2 );

 

If (C1! = '-'){

Printf (wrong command/N ");

Exit (1 );

}

 

If (C2 ='s '){

Reporttype = short;

Strcpy (reptypename, "short ");

} Else if (C2 = 'l '){

Reporttype = long;

Strcpy (reptypename, "long ");

 

Interval = atoi (argv [2]);

Duration = atoi (argv [3]);

}

 

}

 

Gettimeofday (& now, null );

 

Printf ("Status Report: % S/NAT the time of: % s/n", reptypename, ctime (& (now. TV _sec )));

 

/* Output the host name, which is in the/proc/sys/kernel/hostname file */

Printf ("the hostname is :");

Search ("/proc/sys/kernel/hostname ","");

 

Switch (reporttype ){

Case 0:

Search ("/proc/cpuinfo", "model name"); // type and model of the CPU

Search ("/proc/version", ""); // Linux kernel version

Break;

Case 1:

Search ("/proc/STAT", "CPU"); // The total number of CPU times in the user State, system state, and idle state.

Search ("/proc/STAT", "intr"); // Number of disk read/write requests

Search ("/proc/STAT", "ctxt"); // Number of process context switches performed by the kernel

Search ("/proc/STAT", "btime"); // The Last startup time of the system.

Search ("/proc/STAT", "processes"); // number of processes created since startup

Break;

Case 2:

Search ("/proc/meminfo", "memtotal"); // configure the memory size

Search ("/proc/meminfo", "memfree"); // current memory available

While (intervation <duration) {// obtain the average system load

Sleep (interval );

If (get_load_avg () =-1)

Exit (1 );

 

Intervation + = interval;

}

Break;

Default:

Printf ("shocould not Bu here/N ");

}

Return 0;

}

 

Run

./Getinfo

./Getinfo-s (Short Version)

./Getinfo-l Interval Duration (Long Version)

 

 

4. Process status information

The/proc directory contains some directories named after numbers, which are the proc abstraction of the processes running in the current system. There are some files in the corresponding directory that display process-related information. /Proc/self indicates the proc abstraction of the current process. For example, print the command line parameters of the current process:

CAT/proc/self/cmdline

 

Each directory contains the following content:

Cmdline command line parameters

Environ environment variable value

Fd a directory containing all file descriptors

Memory utilization of MEM Process

Stat Process status

The current status of the status process, which is displayed as readable.

CWD current working directory Link

EXE points to the execution command file of the process

Maps memory image

Statm process memory status information

Root link to the root directory of the process

 

 

5. Read the Process status

Because the proc file system has a sub-directory of self, this directory stores the status information of the currently executing process. These status information is stored in the data structure of the kernel. The proc file system provides an interface for interacting with the information. Access the/proc/self/task/"process number"/status file to obtain the information.

 

The following example shows the status of the currently executed process.

 

// Cur_status.c

# Include <stdio. h>

# Include <stdlib. h>

# Include <unistd. h>

# Include <fcntl. h>

# Include <string. h>

 
# Deprecision Max 1024

# Define PID 6

# Define path_size 128

 
Int main (void)

{

File * FP;

Pid_t PID;

Char pid_str [pid];

Char path [path_size];

Char Buf [Max];

 
PID = getpid ();/* obtain the process ID */

Sprintf (pid_str, "% d", pid);/* convert the process ID from a number to a string */

Strcpy (path, "/proc/self/task/");/* splice the path to open the status file under the "/proc/self/task/process ID" directory */

Strcat (path, pid_str );

Strcat (path, "/status ");

 
Fp = fopen (path, "R");/* open the file and open it in read-only mode */

If (FP = NULL ){

Perror ("fail to open ");

Exit (1 );

}

 
While (fgets (BUF, Max, FP )! = NULL)/* read each row sequentially and print */

Printf ("% s", Buf );

 
Fclose (FP);/* close the file */

 
Return 0;

}

 

Run:

Alei @ Alei-desktop :~ /Linux/code/20 $ GCC cur_stat.c-O cur_stat
Alei @ Alei-desktop :~ /Linux/code/20 $./cur_stat
Name: cur_stat
State: R (running)
Tgid: 4443
PID: 4443
Ppid: 4413
Tracerpid: 0
UID: 1000 1000 1000 1000
GID: 1000 1000 1000 1000
Fdsize: 256.
Groups: 4 20 24 46 106 121 122
Vmpeak: 1788 KB
Vmsize: 1788 KB
Vmlck: 0 KB
Vmhwm: 436 KB
Vmrss: 436 KB
Vmdata: 164 KB
Vmstk: 84 KB
Vmexe: 4 kb
Vmlib: 1504 KB
Vmpte: 20 KB
Threads: 1
Sigq: 0/16382
Sigpnd: 0000000000000000
Shdpnd: 0000000000000000
Sigblk: 0000000000000000
Sigign: 0000000000000000
Sigcgt: 0000000000000000
Capinh: 0000000000000000
Cappr: 0000000000000000
Capeff: 0000000000000000
Capbnd: ffffffffffffff
Cpus_allowed: Invalid parameters, 00000003
Cpus_allowed_list: 0-1
Mems_allowed: 1
Mems_allowed_list: 0
Voluntary_ctxt_switches: 1
Nonvoluntary_ctxt_switches: 2

 

 

6. Implement your own ps command

 

// My_ps.c

# Include <stdio. h>

# Include <stdlib. h>

# Include <sys/types. h>

# Include <sys/STAT. h>

# Include <unistd. h>

# Include <dirent. h>

# Include <fcntl. h>

 
# Deprecision Max 1024

# Define path_size 128

 
Int main (void)

{

Dir * dir;

Struct dirent * entry;

File * FP;

Char path [path_size];

Char Buf [Max];

 
Printf ("name/T/tpid/N");/* output header */

 
If (DIR = opendir ("/proc") = NULL) {/* Open the/proc directory */

Perror ("fail to open dir ");

Return-1;

}

 
While (Entry = readdir (DIR ))! = NULL ){


If (Entry-> d_name [0] = '.')/* skips the current directory, and the proc directory does not have a parent directory */

Continue;

/* Skip the system information directory. the directories of all processes are numbers, and the directories of system information are not numbers */

If ('0'> entry-> d_name [0] | entry-> d_name [0]> '9 ')

Continue;


/* Use sprintf to complete the parallel path. Two % s are replaced by the process ID indicated by entry-> d_name */

Sprintf (path, "/proc/% S/task/% S/status", entry-> d_name, entry-> d_name );



Fp = fopen (path, "R");/* open the file */

If (FP = NULL ){

Perror ("fail to open ");

Exit (1 );

}

 
While (fgets (BUF, Max, FP )! = NULL) {/* read each row */

If (BUF [0] = 'n'

& Buf [1] = 'A'

& Buf [2] = 'M'

& Buf [3] = 'E ')

Printf ("% S/T", & Buf [5]);/* Skip '/t' and output status information */


If (BUF [0] = 'P'

& Buf [1] = 'I'

& Buf [2] = 'D '){

Printf ("% s/n", & Buf [4]);/* The loop ends after the PID is output */

Break;

}

}

 
Fclose (FP);/* close the stattus file */

}


Closedir (DIR);/* close the directory */



Return 0;

}

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.