導航:首頁 > 編程系統 > linuxbread

linuxbread

發布時間:2023-05-28 05:31:09

A. c 獲取串口號 c 自動獲取串口號

用C怎麼寫獲取串口的內容

看驅動程序的介面啊

一般是是open(「口名」)

用C/C++寫一扒游個小程序讀取串口接收到賀此銷的數據

你太幸運了,剛好我有一個,你在禪游vc++6.0下測試一下。

/* serrecv.c */

/* Receives and saves a file over a serial port */

/* Last modified: Septemeber 21, 2005 */

/* [goman89] */

#include

#include

#include

/* Function to print out usage information */

void usage(void);

/* Function to set up the serial port settings with the specified baud rate,

no parity, and one stop bit */

void set_up_serial_port(HANDLE h, long baud);

/* Function to receive and save file from serial port */

void get_file_from_serial_port(HANDLE h, char *file_name, unsigned long file_length);

int main(int argc, char **argv)

{

HANDLE serial_port; /* Handle to the serial port */

long baud_rate = 9600; /* Baud rate */

char port_name[] = "COM1:"; /* Name of serial port */

unsigned long file_size; /* Size of file to receive in bytes */

unsigned long bytes_received; /* Bytes received from serial port */

unsigned long file_name_size; /* Size of file name in bytes */

char file_name[256]; /* Name of file to receive */

/* Check mand line */

if (argc == 3)

{

/* Read in baud rate */

if (argv[1][1] != 'b' || sscanf(argv[2], "%ld", &baud_rate) != 1)

{

usage;

exit(0);

}

}

else if (argc != 1)

{

usage;

exit(0);

}

/* Open up a handle to the serial port */

serial_port = CreateFile(port_name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

/* Make sure port was opened */

if (serial_port == INVALID_HANDLE_VALUE)

{

fprintf(stderr, "Error opening port ");

CloseHandle(serial_port);

exit(0);

}

/* Set up the serial port */

set_up_serial_port(serial_port, baud_rate);

/* Receive file name size from serial port */

ReadFile(serial_port, (void *)&file_name_size, sizeof(unsigned long), &bytes_received, NULL);

if (bytes_received != sizeof(unsigned long))

{

fprintf(stderr, "Error getting file name size. ");

CloseHandle(serial_port);

exit(0);

}

/* Receive file name from serial port */

ReadFile(serial_port, (void *)file_name, file_name_size, &bytes_received, NULL);

if (bytes_received != file_name_size)

{

fprintf(stderr, "Error retrieving file name. ");

CloseHandle(serial_port);

exit(0);

}

/* Append NULL terminator to end of string */

file_name[bytes_received] = ''

/* Receive file size from serial port */

ReadFile(serial_port, (void *)&file_size, sizeof(unsigned long), &bytes_received, NULL);

if (bytes_received != sizeof(unsigned long))

{

fprintf(stderr, "Error getting file size. ");

CloseHandle(serial_port);

exit(0);

}

/* Get the file from the serial port */

get_file_from_serial_port(serial_port, file_name, file_size);

/* Print out success information */

printf(" %lu bytes successfully received and saved as %s ", file_size, file_name);

/* Close handle */

CloseHandle(serial_port);

return 0;

}

void usage(void)

{

fprintf(stderr, "Usage: ");

fprintf(stderr, " serrecv [-b baud rate] ");

fprintf(stderr, " Default baud rate is 9600 ");

fprintf(stderr, "tSupported baud rates: 1200, 2400, 4800, 9600, 14400, 19200 ");

return;

}

void set_up_serial_port(HANDLE h, long baud)

{

DCB properties; /* Properties of serial port */

/* Get the properties */

GetmState(h, &properties);

/* Set the baud rate */

switch(baud)

{

case 1200:

properties.BaudRate = CBR_1200;

break;

case 2400:

properties.BaudRate = CBR_2400;

break;

case 4800:

properties.BaudRate = CBR_4800;

break;

case 9600:

properties.BaudRate = CBR_9600;

break;

case 14400:

properties.BaudRate = CBR_14400;

break;

case 19200:

properties.BaudRate = CBR_19200;

break;

case 38400:

properties.BaudRate = CBR_38400;

break;

default:

fprintf(stderr, "Invalid baud rate: %ld ", baud);

usage;

exit(0);

break;

}

/* Set the other properties */

properties.Parity = NOPARITY;

properties.ByteSize = 8;

properties.StopBits = ONESTOPBIT;

SetmState(h, &properties);

return;

}

void get_file_from_serial_port(HANDLE h, char *file_name, unsigned long file_length)

{

FILE *data_file; /* File to create */

unsigned long bytes_left = file_length; /* Bytes left to receive */

unsigned long bytes_received_total = 0; /* Total bytes received */

unsigned long bytes_to_receive; /* Number of bytes to receive */

unsigned long bytes_received; /* Number of bytes receive */

char buffer[200]; /* Buffer to store data */

/* Open the file */

data_file = fopen(file_name, "wb");

/* Quit if file couldn't be opened */

if (data_file == NULL)

{

fprintf(stderr, "Could not create file %s ", file_name);

CloseHandle(h);

exit(0);

}

while (1)

{

/* Determine how many bytes to read */

if (bytes_left == 0)

{

break;

}

else if (bytes_left < 200)

{

bytes_to_receive = bytes_left;

}

else

{

bytes_to_receive = 200;

}

/* Receive data over serial cable */

ReadFile(h, (void *)buffer, bytes_to_receive, &bytes_received, NULL);

if (bytes_received != bytes_to_receive)

{

fprintf(stderr, "Error reading file. ");

CloseHandle(h);

exit(0);

}

/* Save buffer to file */

fwrite((void *)buffer, 1, bytes_received, data_file);

/* Decrement number of bytes left */

bytes_left -= bytes_received;

/* Increment number of bytes received */

bytes_received_total += bytes_received;

/* Print out progress */

printf(" %5lu bytes received.", bytes_received_total);

}

fclose(data_file);

return;

}

C語言變成實現串口收發數據

#include

#include

intmain(void)

{

FILE*fp;

chartemp;

charbuf[100];

if((fp=fopen("3","r"))==NULL)

puts("thiswaydoesn'twork! ");

else

puts("thiswayworks! ");

while(1)

{

temp=0;

fscanf(fp,"%c",&temp);

if(temp!=0)

putchar(temp);

else

Sleep(100);

}

fclose(fp);

return0;

}

以前弄的,好久沒看了,不知到對不對。

還有下面這段:

#include

#include

HANDLEh;

intmain(void)

{

h=CreateFile(TEXT("COM3"),//COM1口

GENERIC_READ|GENERIC_WRITE,//允許讀和寫

0,//獨方式

NULL,

OPEN_EXISTING,//打開而不是創建

0,//同步方式

NULL);

if(h==(HANDLE)-1)

{

printf("打開COM失敗! ");

returnFALSE;

}

else

{

printf("COM打開成功! ");

}

Setupm(h,1024,1024);//輸入緩沖區和輸出緩沖區大小都是1024

COMMTIMEOUTSTimeOuts;

//設讀超時

TimeOuts.ReadIntervalTimeout=1000;

TimeOuts.ReadTotalTimeoutMultiplier=500;

TimeOuts.ReadTotalTimeoutConstant=5000;

//設定寫超時

TimeOuts.WriteTotalTimeoutMultiplier=500;

TimeOuts.WriteTotalTimeoutConstant=2000;

SetmTimeouts(h,&TimeOuts);//設置超時

DCBdcb;

GetmState(h,&dcb);

dcb.BaudRate=9600;//波特率為9600

dcb.ByteSize=8;//每個位元組有8位

dcb.Parity=NOPARITY;//無奇偶校驗位

dcb.StopBits=ONE5STOPBITS;//兩個停止位

SetmState(h,&dcb);

DwordwCount;//讀取的節數

BOOLbReadStat;

while(1)

{

Purgem(h,PURGE_TXCLEAR|PURGE_RXCLEAR);//清緩沖區

charstr[9]={0};

printf("%s ",str);

bReadStat=ReadFile(h,str,9,&wCount,NULL);

if(!bReadStat)

{

printf("

怎麼通過串口讀取51單片機某個地址的數據?請用C語言寫出來。

*

授人以魚,不如授人以漁

*

首先,你要明確在C語中讀取內存址是基於指針。

3.比如讀取內存地址0x22中的數據

C語言中對於內存的訪是基於指,這個毋庸置疑,具體操如下

unsigned int *p= (unsigned int*)0x22 ;//定義針,並且使指針指向了0x22這個 內存地址;

那麼*p就是最終你要讀取的數據了。

4.至於如何通過串口顯示到電腦我就不多了(這不是難點),據你都知道了,寫到串口 緩沖區,在串口調試助手下就可以看到。

5.雖然沒有貼出具體代碼,但這裡面的思想可以讓你解決

標簽:作文經典 上一篇:描寫毛毛蟲的詞語 描寫毛毛蟲行動的詞語 下一篇:成語誤用褒貶的例子 褒貶誤用的成語

linux下如何使用c/c++實現檢測新增串口,並讀取串口號

Linux下面有設文件

串口裝好驅動後 會顯示在dev下

然後對這個

C語言中如何對串口進行操作

C語言會有操作串口的庫函數的,按照串口庫數標識實現調

電腦上的串口號是什麼意思

串口叫做串列介面,也串列通信介面,按電氣標准及協議來分包括RS-232-C、RS-422、RS485、USB等。 RS-232-C、RS-422與RS-485標准對介面的電氣特性做出規定,不涉及接插件、電纜或協議。USB是近幾年發展起來的新型介面標准,主要應用於速數據傳輸域。 RS-232-C:也稱標准串口,是目前最常用的一種串列通訊介面。它是在1970年由美國電子工業協會(EIA)聯合貝爾系統、 數據機廠家及計算機終端生產廠共同制定的用於串列通訊的標 准。它的名是「數據終端設備(DTE)和數據通訊設備(DCE)之間 行二進制數據交換介面技術標准」。傳統的RS-232-C介面標准有22根線,採用標准25芯D型插頭座。後來的PC上使用簡化了的9芯D插座。現在應用中25芯插頭已很少採用。現在的電腦般有兩個串列口:COM1和COM2,你到計算機後面能看到9針D形介面就是了。現在有很多手數據線或者物流接收器都採用COM

如何用C語言寫一個讀、寫串口的程序?

大致過程就是

配置串口通信,包串口號、波特、驗位、停止位這些信息;

打開串口,和打開文件一樣,在Linux是這樣,Windows下沒試過,估計也差不多;

發送數據,即寫串口,就跟寫文件類似;

讀取

編寫單片機串口收發數據的完整程序(C語言編寫)

我用的新唐晶元,8051內核,跟51差不多,望採納

void UART_Initial (void)

{

P02_Quasi_Mode; //Setting UART pin as Quasi mode for tran *** it

P16_Quasi_Mode; //Setting UART pin as Quasi mode for tran *** it

SCON_1 = 0x50; //UART1 Mode1,REN_1=1,TI_1=1

T3CON = 0x08; //T3PS2=0,T3PS1=0,T3PS0=0(Prescale=1), UART1 in MODE 1

clr_BRCK;

RH3 = HIBYTE(65536 - (1000000/u32Baudrate)-1); /*16 MHz */

RL3 = LOBYTE(65536 - (1000000/u32Baudrate)-1); /*16 MHz */

set_TR3; //Trigger Timer3

}

以上是初始化的

void Send_Data_To_UART1(UINT8 c)

{

TI_1 = 0;

SBUF_1 = c;

while(TI_1==0);

}

這個是發送

void UART_isr (void) interrupt 4 //

怎樣在WINDOWS下用C語言編寫串口接收數據程序

#include

#include

int main(void)

{

FILE *fp;

char temp;

char buf[100];

if((fp = fopen("3","r")) == NULL)

puts("this way doesn't work! ");

else

puts("this way works! ");

while(1)

{

temp = 0;

fscanf(fp,"%c",&temp);

if(temp != 0)

putchar(temp);

else

Sleep(100);

}

fclose(fp);

return 0;

}

以前的,好久看,不知到對不對。

還下面這段:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

#include

#include

HANDLE h;

int main(void)

{

h=CreateFile(TEXT("COM3"),//COM1口

GENERIC_READ|GENERIC_WRITE, //允許讀和寫

0, //獨占方式

NULL,

OPEN_EXISTING, //打開而不是建

0, //同步式

NULL);

if(h==(HANDLE)-1)

{

printf("打開COM失敗! ");

return FALSE;

}

else

{

printf("COM打開成功! ");

}

Setupm(h,1024,1024); //輸入緩沖區和輸出緩沖區的大小都是1024

COMMTIMEOUTS TimeOuts;

//定讀超時

TimeOuts.ReadIntervalTimeout=1000;

TimeOuts.ReadTotalTimeoutMultiplier=500;

TimeOuts.ReadTotalTimeoutConstant=5000;

//設定寫超時

TimeOuts.WriteTotalTimeoutMultiplier=500;

TimeOuts.WriteTotalTimeoutConstant=2000;

SetmTimeouts(h,&TimeOuts); //設置超時

DCB dcb;

GetmState(h,&dcb);

dcb.BaudRate=9600; //波特率為9600

dcb.ByteSize=8; //每個位元組有8位

dcb.Parity=NOPARITY; //無奇偶校驗位

dcb.StopBits=ONE5STOPBITS; //兩個停止位

SetmState(h,&dcb);

DWORD wCount;//讀取的位元組

BOOL bReadStat;

while(1)

{

Purgem(h,PURGE_TXCLEAR|PURGE_RXCLEAR); //清空緩沖區

char str[9]={0};

printf("%s ",str);

bReadStat=ReadFile(h,str,9,&wCount,NULL);

if(!bReadStat)

{

printf("讀串口

標簽:作文經典 上一篇:描寫毛毛蟲的詞語 描寫毛毛蟲行動的詞語 下一篇:成語誤用褒貶的例子 褒貶誤用的成語

B. 繼續問linux系統下的題目

TCSH shell不同於其他的shell,因為控制結構更符合程序設計語言的格式.例如TCSH 的test條件的控制結構是表達式,而不是linux命令,得到的值是邏輯值true或false,TCSH的表達式與C語言中的表達式基本相銷扮冊同.

一,TCSH shell變數,腳本,參數用戶可以在shell中定義變數,為變數賦值以及引用腳本參數.TCSH使用set,@,setenv定義一變數,也可以用相同的方法定義數值變數和數組,用戶通過@命令定義的數值變數來進行算術運算,用戶使用圓括弧()和方括弧[]定義和引用數組.腳本也可以用相同的方法操作,但是有個例外,盡虧宏管可以用echo命令輸出提示符,但沒有read命令處理輸入,相反,必須重定向到一個變數里.

二,腳本輸入和腳本輸出: $ <用戶能夠在腳本范圍中定義和使用變數.在下例中,使用文本編輯器把賦值操作和echo之類的linux命令放在一個文件中.然後, 可以產生可執行文件並像其他命令一樣在命令行中執行它,要記住添加可執行許可權,必須使用帶u+x參數的chmod命令或者帶絕對參數700的chmod命令.在腳本中,可以使用echo命令去輸出數據,但是,必須通過重定向標准輸入把輸入讀入變數.在TCSH中沒有linux read命令的比較版本.記住TCSH全部的腳本文件的第一行的第一個字元必須是"#"字元.如:
#
#display "hello"
set string="hello"
echo The value of string is $string

set命令和重定向符號結合$<將用戶輸入的任何數據讀入標準的輸入中.下例中,把用戶輸入讀入string變數中.
%set string=$<
abc
%echo $string
abc

能夠把提示符放置到相同的行用作echo的輸入.TCSH使用一個特殊的選項-n,將消除輸出字元串中的回車符.游標將保留在輸出字元串的結尾處.
%echo -n please enter a string

%cat hello
#
echo -n "please enter a string:"
set string=$<
echo "the value of string is $string"
%chmod u+x hello
%hello
please enter a string:hello
the value of string is hello
%

三,操作符TCSH有一系列標準的賦值,算術缺備和關系運算以及重定向和後台操作等函數賦值運算符 功能說明
= 賦值操作
+= 先加再賦值
-= 先減再賦值
*= 先乘再賦值
/= 先除再賦值
%= 取余再賦值
++ 自增量1
-- 自減量1
算術運算符 說明
- 負號
+ 加法
- 減法
* 乘法
/ 除法
% 取余
關系運算符 說明
> 大於
< 小於
>= 大於等於
<= 小於等於
!= 不等於
== 等於
重定向和管道符TCSH支持標准輸入和標准輸出的重定向和管道操作.如果設置了noclobber特徵,要用重定向操作重寫當前文件,需要用符號>!代替>

四,控制結構同其他shell一樣,TCSH也有一系列的控制結構控制腳本的命令的執行.while和if控制結構是最常用的控制結構.switch和foreach是更專用的控制結構.switch是if條件的限定形式,檢查數值是否等於一系列可能的數值中的一個數值.foreach是循環結構的限定形式.瀏覽數值列表,給變數賦新的數值.TCSH不同的控制結構列表:

條件控制結構; 功能
if (expression) then 如果expression為真,則執行commands commands
endif

if (expression) then 如果expression為真,則執行command1,否則執行command1 command2.
else
command2
endif

switch (string) 允許在幾條替換命令中選擇,string為不同的模式case pattern:
commands
breadsw
default:
commands
endsw

循環控制結構: 功能while (expression) 只要expression為真,則重復執行commands,commands 直到expression為假時跳出循環end

foreach variable (argument-list)迭代循環獲得和argument-list中一樣多的參數commands (每次循環variable被設置為列表的下一個參數;end 操作方式同BSH)

TCSH中的控制結構有別於其他的shell,因為它更接近編程語言(C).TCSH的條件表達式的值為true/false.BASH和TCSH主要區別在於TCSH的結構不可重定向或進行管道輸出.

五,測試表達式;()if和while控制結構把表達式用作測試.表達式測試的結果為非零(1)表示真,而零(0)表示假(跟BASH相反).測試表達式可由算術/字元串比較,但是字元串只能作相等和不相等的比較.而且表達式必須要在()括弧內.如:
if (expression) then
command
endif
TCSH有一系列的運算符來分別對字元串進行測試比較.正則表達式可以包含shell腳本的指令的字元串.如:
if ( $var =~[Hh]* ) then #如果變數$var以字母是大寫/小寫Hh開頭,的字元串
echo information #執行命令
endif #結束
有很多測試文件的操作與BASH完全相同.如:
if ( -r myfile ) then #測試myfile是否可讀
echo info
endif

測試表達式的基本操作:
字元串比較: 功能
== 是否相等,若相等返回真
!= 是否不等,若不等返回真
=~ 字元串和模式進行測試是否相等(模式為任意正則表達式)
!~ 字元串和模式測試是否不等(模式為任意正則表達式)文件測試: 功能
-e 測試文件是否存在
-r 測試文件是否可讀
-w 測試文件是否可寫
-x 測試文件是否可執行
-d 測試文件名是否為目錄
-f 測試文件是否為普通文件
-o 測試文件是否被用戶所擁有
-z 測試文件是否為空
邏輯運算符: 功能
&& 與運算,兩個條件同時蠻族
|| 或運算,有一個條件滿足
! 取反

六,TCSH內建命令
1,數字變數:@
在TCSH中,用@命令代替set命令來聲明數字變數,然後進行算術,關系和位操作,數字和字元串變數是兩個不同的對象,需要用不同的方法管理,不能把set用於數值變數的設置@命令由關鍵詞,變數名,賦值運算符和表達式構成.如:
%@ num=10 #注意空格
%@ sum=2 * ($num + 3)
%echo $sum
%26

2,alias
格式:alias [name[command]]
關鍵詞alias 別名name 引用的命令command
如:
alias list ls
alias list 'ls -l'

3,argv
當腳本被執行時,命令行中的單詞被分析並放入argv數組中.argv[0],argv[1]...argv[n],其中argv[0]保存命令名,argv[1]保存命令的第一個參數,argv[n]命令的第n個參數.argv數組元素可縮寫元素號碼,前面加$.如:$argv[1]寫為$1.$argv[*]寫為$*.#argv參數標識符包含輸入在命令行中的參數號碼,可檢查$#argv變數.如:
arglist
#
echo "The number of arguments entered is $#argv"
echo "The list of arguments is : $argv[*]"

%tcsh arglist a b c
The number of arguments entered is 3
The list of arguments is : a b c
argv變數列表:
命令行參數 說明
$argv[0]或$0 命令名
$argv[n]或$n 從1($1-$)開始的第n個命令行參數
$argv[*]或$* 從1開始的所有命令行參數
$#argv或$# 命令行參數的計數

4,bg
格式:bg [%job]
bg命令把指定的任務放入後台.如果此任務已經停止,則繼續執行,如果沒有參數,將當前任務放入後台.(詳細用法與BASH相同此處略)

5,break
格式:break
break命令用於退出最接近的foreach/while循環過程.執行同一行中其他的命令.

6,breaksw
格式:breaksw
可以從switch語句處中斷,在endsw後繼續執行.

7,builtins
列出全部shell的內建命令表.

8,cd
格式:cd [-p][-l][-nl -v][name]如果給出目錄名,此命令把name設置為當前目錄,如果命令中沒有name,當前目錄自動設置成用戶主目錄.用於name的"-"引用上一級目錄,如果參數name沒有給出子目錄,或不是全路徑,或使用./或../引用當前目錄及父目錄,那麼就檢查在cdpath shell變數中列出的目錄來尋找該目錄名.如果此操作失敗,將檢查shell變數中是否保存著的目錄路徑名.
用-p選項,linux顯示目錄列表, 用-l,-n,-v選項與用在dirs命令中的選項完全相同.默認選項-p.

9,continue
此命令繼續執行最靠近while/foreach語句.當前行其餘的命令被執行.

10,dirs
格式:dirs [-l][-n|-v]
dirs -S|-L [filename]
dir -c
如果不帶參數,dirs將顯示目錄列表,列表開頭被列在作側,第一個目錄是當前目錄.帶-l選項,用戶主目錄中的全部子目錄被展開,輸入項在到達屏幕邊緣時,-n選項隱藏輸入項,-v選項顯示每一行的輸入項入口,-c選項將清除目錄列表,-S選項可以把目錄列表作為一系列的cd和pushed命令保存在文件中,-L選項可以從指定的文件中將cd和pushed命令讀入,該文件包含-S選項所存儲的cd和pushed命令.如果沒有指定的文件名,將使用賦值到dirsfile shell變數中的文件名.如果沒有設置dirsfile,將使用~/.cshdirs,在啟動時注冊shell將對dirs -L求值,如果設置了savedirs,退出前使用dirs -S,由於在~/.cshdirs之前,僅僅~/.tcshrc是正常來源,dirsfile應該以~/.tcshrc設置而不是以~/.login設置.

11,echo
格式:echo [-n] word/string此命令把每個單詞或字元串寫入shell的標准輸出.可設置echostyle shell變數來模擬選項以及BSD的換碼序列或者echo的System V 版本.

12,eval
格式:eval argument...
此命令把參數作
一,TCSH shell變數,腳本,參數
用戶可以在shell中定義變數,為變數賦值以及引用腳本參數.TCSH使用set,@,setenv定
義一變數,也可以用相同的方法定義數值變數和數組,用戶通過@命令定義的數值變數來
進行算術運算,用戶使用圓括弧()和方括弧[]定義和引用數組.腳本也可以用相同的方
法操作,但是有個例外,盡管可以用echo命令輸出提示符,但沒有read命令處理輸入,相
反,必須重定向到一個變數里.

二,腳本輸入和腳本輸出: $ <
用戶能夠在腳本范圍中定義和使用變數.在下例中,使用文本編輯器把賦值操作和echo
之類的linux命令放在一個文件中.然後, 可以產生可執行文件並像其他命令一樣在命
令行中執行它,要記住添加可執行許可權,必須使用帶u+x參數的chmod命令或者帶絕對參
數700的chmod命令.在腳本中,可以使用echo命令去輸出數據,但是,必須通過重定向標
准輸入把輸入讀入變數.在TCSH中沒有linux read命令的比較版本.記住TCSH全部的腳
本文件的第一行的第一個字元必須是"#"字元.
如:
#
#display "hello"
set string="hello"
echo The value of string is $string

set命令和重定向符號結合$<將用戶輸入的任何數據讀入標準的輸入中.下例中,把用戶
輸入讀入string變數中.
%set string=$<
abc
%echo $string
abc

C. fedora 12 沒有sar命令

sar是Linux外部安裝的工具,可以到http://pagesperso-orange.fr/sebastien.godard/download.html去下載
1 安裝
tar zxvf xxx.tar.gz
cd xxx
./configure
make
make install
2 使用
pidstat 2 5
//每隔2秒,顯示5次,所有活動進程的CPU使用情況
pidstat -p 3132 2 5
//每隔2秒,顯示5次,PID為3132的進程的CPU使用情況顯示
pidstat -p 3132 2 5 -r
//每隔2秒,顯示5次,PID為3132的進程的內存使用情況顯示

查看CPU使用情況

sar 2 5
//每隔2秒,顯示5次,CPU使用的情況

%usr:CPU處在用戶模式下的時間百分比。
%sys:CPU處在系統模式下的時間百分比。
%wio:CPU等待輸入輸出完成時間的百分比。
%idle:CPU空閑時間百分比。

在所有的顯示中,我們應主要注意%wio和%idle,%wio的值過高,表示硬碟存在I/O瓶頸,
%idle值高,表示CPU較空閑,如果%idle值高但系統響應慢時,有可能是CPU等待分配內存,
此時應加大內存容量。%idle值如果持續低於10,那麼系統的CPU處理能力相對較低,表
明慧指握系統中最需要解決的資源是CPU。

sar 1 10 > data.txt
//每隔1秒,寫入10次,把CPU使用數據保存到data.txt文件中。
sar 1 0 -e 15:00:00 > data.txt
//每隔1秒記錄CPU的使用情況,直到15點,數據將保存到data.txt文件中。(-e 參數表示結束時間,注意時間格式:必須為hh:mm:ss格式)
sar 1 0 -r -e 15:00:00 > data.txt
//每隔1秒記錄內存使用情況,直到15點,數據將保存到data.txt文件中。
sar 1 0 -n DEV -e 15:00:00 > data.txt
//每隔1秒記錄網路使用情況,直到15點,數據將保存到data.txt文件中。

例二:使用命行sar -v t n

例如,每30秒采樣一次,連續采樣5次,觀察核心表的狀態,需鍵入如下命令:

# sar -v 30 5

屏幕顯示:
SCO_SV scosysv 3.2v5.0.5 i80386 10/01/2001
10:33:23 proc-sz ov inod-sz ov file-sz ov lock-sz (-v)
10:33:53 305/ 321 0 1337/2764 0 1561/1706 0 40/ 128
10:34:23 308/ 321 0 1340/2764 0 1587/1706 0 37/ 128
10:34:53 305/ 321 0 1332/2764 0 1565/1706 0 36/ 128
10:35:23 308/ 321 0 1338/2764 0 1592/1706 0 37/ 128
10:35:53 308/ 321 0 1335/2764 0 1591/1706 0 37/ 128

顯示內容包括:

proc-sz:目前核心中正在使用或分配的進程表的表項數,由核心參數MAX-PROC控制。

inod-sz:目前慶前核心中正在使用或分配的i節點表的表項數,由核心參數
MAX-INODE控制。

file-sz: 目前核心中正在使用或分配的文件表的表項數,由核心參數MAX-FILE控
制。

ov:溢出出現的次數。

Lock-sz:目前核心中正在使用或分配的記錄加鎖的表項數,逗悉由核心參數MAX-FLCKRE
控制。

顯示格式為

實際使用表項/可以使用的表項數

顯示內容表示,核心使用完全正常,三個表沒有出現溢出現象,核心參數不需調整,如
果出現溢出時,要調整相應的核心參數,將對應的表項數加大。

例三:使用命行sar -d t n

例如,每30秒采樣一次,連續采樣5次,報告設備使用情況,需鍵入如下命令:

# sar -d 30 5

屏幕顯示:

SCO_SV scosysv 3.2v5.0.5 i80386 10/01/2001
11:06:43 device %busy avque r+w/s blks/s avwait avserv (-d)
11:07:13 wd-0 1.47 2.75 4.67 14.73 5.50 3.14
11:07:43 wd-0 0.43 18.77 3.07 8.66 25.11 1.41
11:08:13 wd-0 0.77 2.78 2.77 7.26 4.94 2.77
11:08:43 wd-0 1.10 11.18 4.10 11.26 27.32 2.68
11:09:13 wd-0 1.97 21.78 5.86 34.06 69.66 3.35
Average wd-0 1.15 12.11 4.09 15.19 31.12 2.80

顯示內容包括:

device: sar命令正在監視的塊設備的名字。
%busy: 設備忙時,傳送請求所佔時間的百分比。
avque: 隊列站滿時,未完成請求數量的平均值。
r+w/s: 每秒傳送到設備或從設備傳出的數據量。
blks/s: 每秒傳送的塊數,每塊512位元組。
avwait: 隊列占滿時傳送請求等待隊列空閑的平均時間。
avserv: 完成傳送請求所需平均時間(毫秒)。

在顯示的內容中,wd-0是硬碟的名字,%busy的值比較小,說明用於處理傳送請求的有
效時間太少,文件系統效率不高,一般來講,%busy值高些,avque值低些,文件系統
的效率比較高,如果%busy和avque值相對比較高,說明硬碟傳輸速度太慢,需調整。

例四:使用命行sar -b t n

例如,每30秒采樣一次,連續采樣5次,報告緩沖區的使用情況,需鍵入如下命令:

# sar -b 30 5

屏幕顯示:

SCO_SV scosysv 3.2v5.0.5 i80386 10/01/2001
14:54:59 bread/s lread/s %rcache bwrit/s lwrit/s %wcache pread/s pwrit/s (-b)
14:55:29 0 147 100 5 21 78 0 0
14:55:59 0 186 100 5 25 79 0 0
14:56:29 4 232 98 8 58 86 0 0
14:56:59 0 125 100 5 23 76 0 0
14:57:29 0 89 100 4 12 66 0 0
Average 1 156 99 5 28 80 0 0

顯示內容包括:

bread/s: 每秒從硬碟讀入系統緩沖區buffer的物理塊數。
lread/s: 平均每秒從系統buffer讀出的邏輯塊數。
%rcache: 在buffer cache中進行邏輯讀的百分比。
bwrit/s: 平均每秒從系統buffer向磁碟所寫的物理塊數。
lwrit/s: 平均每秒寫到系統buffer邏輯塊數。
%wcache: 在buffer cache中進行邏輯讀的百分比。
pread/s: 平均每秒請求物理讀的次數。
pwrit/s: 平均每秒請求物理寫的次數。

在顯示的內容中,最重要的是%cache和%wcache兩列,它們的值體現著buffer的使用效
率,%rcache的值小於90或者%wcache的值低於65,應適當增加系統buffer的數量,buffer
數量由核心參數NBUF控制,使%rcache達到90左右,%wcache達到80左右。但buffer參數
值的多少影響I/O效率,增加buffer,應在較大內存的情況下,否則系統效率反而得不到
提高。

例五:使用命行sar -g t n

例如,每30秒采樣一次,連續采樣5次,報告串口I/O的操作情況,需鍵入如下命令:

# sar -g 30 5

屏幕顯示:

SCO_SV scosysv 3.2v5.0.5 i80386 11/22/2001
17:07:03 ovsiohw/s ovsiodma/s ovclist/s (-g)
17:07:33 0.00 0.00 0.00
17:08:03 0.00 0.00 0.00
17:08:33 0.00 0.00 0.00
17:09:03 0.00 0.00 0.00
17:09:33 0.00 0.00 0.00
Average 0.00 0.00 0.00

顯示內容包括:

ovsiohw/s:每秒在串口I/O硬體出現的溢出。

ovsiodma/s:每秒在串口I/O的直接輸入輸出通道高速緩存出現的溢出。

ovclist/s :每秒字元隊列出現的溢出。

在顯示的內容中,每一列的值都是零,表明在采樣時間內,系統中沒有發生串口I/O溢
出現象。

D. 實現雙機通信的C語言代碼

代碼要求是什麼? 基本實現 ping 的功能?

ping 代碼

#include <windows.h>
#include <winsock2.h>

#define IP_RECORD_ROUTE 0x7

#define ICMP_ECHO 8
#define ICMP_ECHOREPLY 0
#define ICMP_MIN 8 // minimum 8 byte icmp packet (just header)

#define DEF_PACKET_SIZE 32 // Default packet size
#define MAX_PACKET 60000 // Max ICMP packet size 1024
#define MAX_IP_HDR_SIZE 60 // Max IP header size w/options

typedef struct _iphdr
{
unsigned int h_len:4; // Length of the header
unsigned int version:4; // Version of IP
unsigned char tos; // Type of service
unsigned short total_len; // Total length of the packet
unsigned short ident; //鄭旅 Unique identifier
unsigned short frag_and_flags; // Flags
unsigned char ttl; // Time to live
unsigned char proto; // Protocol (TCP, UDP etc)
unsigned short checksum; // IP checksum

unsigned int sourceIP;
unsigned int destIP;
} IpHeader;

//
/棚叢物/ ICMP header structure
//
typedef struct _icmphdr
{
BYTE i_type;
BYTE i_code; // Type sub code
USHORT i_cksum;
USHORT i_id;
USHORT i_seq;
// This is not the standard header, but we reserve space for time
ULONG timestamp;
} IcmpHeader;

//
// IP option header - use with socket option IP_OPTIONS
//
typedef struct _ipoptionhdr
{
unsigned char code; // Option type
unsigned char len; /鏈液/ Length of option hdr
unsigned char ptr; // Offset into options
unsigned long addr[9]; // List of IP addrs
} IpOptionHeader;

//
// Function: FillICMPData
//
// Description:
// Helper function to fill in various fields for our ICMP request
//
void FillICMPData(char *icmp_data, int datasize)
{
IcmpHeader *icmp_hdr = NULL;
char *datapart = NULL;

icmp_hdr = (IcmpHeader*)(icmp_data); //+sizeof(IpHeader)
icmp_hdr->i_type = ICMP_ECHO; // Request an ICMP echo
icmp_hdr->i_code = 0;
icmp_hdr->i_id = (USHORT)GetCurrentProcessId();
icmp_hdr->i_cksum = 0;
icmp_hdr->i_seq = 0;

datapart = icmp_data + sizeof(IcmpHeader);
//
// Place some junk in the buffer
//
memset(datapart,'E', datasize - sizeof(IcmpHeader));
}
//---------------------------------------------------------------------------

USHORT checksum(USHORT *buffer, int size)
{
unsigned long cksum=0;

while (size > 1)
{
cksum += *buffer++;
size -= sizeof(USHORT);
}
if (size)
{
cksum += *(UCHAR*)buffer;
}
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >>16);
return (USHORT)(~cksum);
}
//---------------------------------------------------------------------------

void DecodeIPOptions(char *buf, int bytes, void CALLBACK (*pDis)(const char* szMes))
{
IpOptionHeader *ipopt = NULL;
IN_ADDR inaddr;
int i;
HOSTENT *host = NULL;
char szMesBuffer[255];
ipopt = (IpOptionHeader *)(buf + 20);

if (pDis != NULL)
{
pDis("RR: ");
}
for(i = 0; i < (ipopt->ptr / 4) - 1; i++)
{
inaddr.S_un.S_addr = ipopt->addr[i];
if (i != 0)
{
if (pDis != NULL)
{
pDis(" ");
}
}
host = gethostbyaddr((char *)&inaddr.S_un.S_addr, sizeof(inaddr.S_un.S_addr), AF_INET);
if (host)
{
if (pDis != NULL)
{
wsprintf(szMesBuffer, "(%-15s) %s", inet_ntoa(inaddr), host->h_name);
pDis(szMesBuffer);
}
}
else
{
if (pDis != NULL)
{
wsprintf(szMesBuffer, "(%-15s)", inet_ntoa(inaddr));
pDis(szMesBuffer);
}
}
}
return;
}
//---------------------------------------------------------------------------

int DecodeICMPHeader(char *buf, int bytes, struct sockaddr_in *from, void CALLBACK (*pDis)(const char* szMes))
{
IpHeader *iphdr = NULL;
IcmpHeader *icmphdr = NULL;
unsigned short iphdrlen;
DWORD tick;
static int icmpcount = 0;
char szMesBuffer[255];
char szMesBuffer1[255];

iphdr = (IpHeader *)buf;
// Number of 32-bit words * 4 = bytes
iphdrlen = iphdr->h_len * 4;
tick = GetTickCount();

if ((iphdrlen == MAX_IP_HDR_SIZE) && (!icmpcount))
DecodeIPOptions(buf, bytes, pDis);

if (bytes < iphdrlen + ICMP_MIN)
{
//printf("Too few bytes from %s\n", inet_ntoa(from->sin_addr));
if (pDis != NULL)
{
wsprintf(szMesBuffer, "Too few bytes from %s", inet_ntoa(from->sin_addr));
pDis(szMesBuffer);
}
}
icmphdr = (IcmpHeader*)(buf + iphdrlen);

if (icmphdr->i_type != ICMP_ECHOREPLY)
{
//printf("nonecho type %d recvd\n", icmphdr->i_type);
if (pDis != NULL)
{
wsprintf(szMesBuffer, "nonecho type %d recvd", icmphdr->i_type);
pDis(szMesBuffer);
}
return -1;
}
// Make sure this is an ICMP reply to something we sent!
//
if (icmphdr->i_id != (USHORT)GetCurrentProcessId())
{
//printf("someone else's packet!\n");
if (pDis != NULL)
{
pDis("someone else's packet!");
}
return -1;
}
//printf("%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
//printf(" icmp_seq = %d. ", icmphdr->i_seq);
//printf(" time: %d ms", tick - icmphdr->timestamp);
//printf("\n");
if (pDis != NULL)
{
wsprintf(szMesBuffer, "%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
wsprintf(szMesBuffer1, " icmp_seq = %d. ", icmphdr->i_seq);
lstrcat(szMesBuffer, szMesBuffer1);
wsprintf(szMesBuffer1, " time: %d ms", tick - icmphdr->timestamp);
lstrcat(szMesBuffer, szMesBuffer1);
wsprintf(szMesBuffer1, " TTL = %d", iphdr->ttl);
lstrcat(szMesBuffer, szMesBuffer1);
pDis(szMesBuffer);
}

icmpcount++;
return tick - icmphdr->timestamp;
}
//---------------------------------------------------------------------------

ping(const char* szTargetAddress, int iDataSize, int iTimeOut, int iTimes, bool bReply, void CALLBACK (*pDis)(const char* szMes))
{
WSADATA wsaData;
SOCKET sockRaw = INVALID_SOCKET;
struct sockaddr_in dest,
from;
int bread,
fromlen = sizeof(from),
timeout = iTimeOut,
ret;
char *icmp_data = NULL,
*recvbuf = NULL;
unsigned int addr = 0;
USHORT seq_no = 0;
struct hostent *hp = NULL;
IpHeader ip_header;
IpOptionHeader ipopt;
char szMesBuffer[255];

if (timeout > 3000)
timeout = 3000;
else if (timeout < 100)
timeout = 100;

if (pDis != NULL)
{
wsprintf(szMesBuffer, "ping %s with %d bytes of data:", szTargetAddress, iDataSize);
pDis(szMesBuffer);
}

if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
//printf("WSAStartup() failed: %d\n", GetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "WSAStartup() failed: %d", GetLastError());
pDis(szMesBuffer);
}
return -1;
}

sockRaw = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, WSA_FLAG_OVERLAPPED);
if (sockRaw == INVALID_SOCKET)
{
//printf("WSASocket() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "WSASocket() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}

// Set the send/recv timeout values
//
bread = setsockopt(sockRaw, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
if(bread == SOCKET_ERROR)
{
//printf("setsockopt(SO_RCVTIMEO) failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "setsockopt(SO_RCVTIMEO) failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
bread = setsockopt(sockRaw, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
if (bread == SOCKET_ERROR)
{
//printf("setsockopt(SO_SNDTIMEO) failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "setsockopt(SO_SNDTIMEO) failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
memset(&dest, 0, sizeof(dest));
//
// Resolve the endpoint's name if necessary
//
dest.sin_family = AF_INET;
if ((dest.sin_addr.s_addr = inet_addr(szTargetAddress)) == INADDR_NONE)
{
if ((hp = gethostbyname(szTargetAddress)) != NULL)
{
memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);
dest.sin_family = hp->h_addrtype;
//printf("dest.sin_addr = %s\n", inet_ntoa(dest.sin_addr));
if (pDis != NULL)
{
wsprintf(szMesBuffer, "dest.sin_addr = %s", inet_ntoa(dest.sin_addr));
pDis(szMesBuffer);
}
}
else
{
//printf("gethostbyname() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "gethostbyname() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
}
//
// Create the ICMP packet
//

int datasize = iDataSize;
if (datasize < 0)
datasize = DEF_PACKET_SIZE;

datasize += sizeof(IcmpHeader);

if (datasize > MAX_PACKET)
datasize = MAX_PACKET;

icmp_data = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_PACKET);
recvbuf = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_PACKET);
if (!icmp_data)
{
//printf("HeapAlloc() failed: %d\n", GetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "HeapAlloc() failed: %d", GetLastError());
pDis(szMesBuffer);
}
return -1;
}
//memset(icmp_data, 0, datasize); //, MAX_PACKET
FillICMPData(icmp_data, datasize);
//
// Start sending/receiving ICMP packets
//
int nCount = 0;
int iReceiveCount = 0;
if (iTimes < 2)
{
iTimes = 2;
}
while(1)
{
int bwrote;

if (nCount++ == iTimes)
break;

((IcmpHeader*)icmp_data)->i_cksum = 0;
((IcmpHeader*)icmp_data)->timestamp = GetTickCount();
((IcmpHeader*)icmp_data)->i_seq = seq_no++;
((IcmpHeader*)icmp_data)->i_cksum = checksum((USHORT*)icmp_data, datasize);

bwrote = sendto(sockRaw, icmp_data, datasize, 0, (struct sockaddr*)&dest, sizeof(dest));
if (bwrote == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAETIMEDOUT)
{
//printf("timed out\n");
if (pDis != NULL)
{
wsprintf(szMesBuffer, "timed out");
pDis(szMesBuffer);
}
continue;
}
//printf("sendto() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "sendto() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
if (bwrote < datasize)
{
//printf("Wrote %d bytes\n", bwrote);
if (pDis != NULL)
{
wsprintf(szMesBuffer, "Wrote %d bytes", bwrote);
pDis(szMesBuffer);
}
}
bread = recvfrom(sockRaw, recvbuf, MAX_PACKET, 0, (struct sockaddr*)&from, &fromlen);
if (bread == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAETIMEDOUT)
{
//printf("timed out\n");
if (pDis != NULL)
{
wsprintf(szMesBuffer, "timed out");
pDis(szMesBuffer);
}
continue;
}
//printf("recvfrom() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "recvfrom() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
DecodeICMPHeader(recvbuf, bread, &from, pDis); //return replay time ms
iReceiveCount++;

Sleep(50);//1000
}
// Cleanup
//
if (sockRaw != INVALID_SOCKET)
closesocket(sockRaw);
HeapFree(GetProcessHeap(), 0, recvbuf);
HeapFree(GetProcessHeap(), 0, icmp_data);

WSACleanup();
if (pDis != NULL && bReply)
{
pDis(" ");
nCount--;
wsprintf(szMesBuffer, "Packets: Sent = %d, Received = %d, Lost = %d (%d%s", nCount, iReceiveCount, nCount - iReceiveCount, (nCount - iReceiveCount) * 100 / nCount, "% loss)");
pDis(szMesBuffer);
pDis(" ");
}

return 0;
}
//---------------------------------------------------------------------------

調用方法:

ping(
szTargetAddress, //目標地址 //IP 或網址
iDataSize, //數據包大小
iTimeOut, //延時
iTimes, //發送次數
bReply, //是否顯示信息
CALLBACK (*pDis)(const char* szMes)//顯示信息的函數指針
);

void pingMessage(const char* szMes);

main()
{
ping("127.0.0.1", 32, 500, 5, true, pingMessage);
}

void pingMessage(const char* szMes)
{
printf("%s\n", szMes);
}

E. LINUX下ping 程序如何寫

/******************************************************************************\
* ping.c - Simple ping utility using SOCK_RAW
*
* This is a part of the Microsoft Source Code Samples.
* Copyright 1996-1997 Microsoft Corporation.
* All rights reserved.
* This source code is only intended as a supplement to
* Microsoft Development Tools and/or WinHelp documentation.
* See these sources for detailed information regarding the
* Microsoft samples programs.
\******************************************************************************/

#pragma pack(4)

#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>

#define ICMP_ECHO 8
#define ICMP_ECHOREPLY 0

#define ICMP_MIN 8 // minimum 8 byte icmp packet (just header)

/* The IP header */
typedef struct iphdr {
unsigned int h_len:4; // length of the header
unsigned int version:4; // Version of IP
unsigned char tos; // Type of service
unsigned short total_len; // total length of the packet
unsigned short ident; // unique identifier
unsigned short frag_and_flags; // flags
unsigned char ttl;
unsigned char proto; // protocol (TCP, UDP etc)
unsigned short checksum; // IP checksum

unsigned int sourceIP;
unsigned int destIP;

}IpHeader;

//
// ICMP header
//
typedef struct _ihdr {
BYTE i_type;
BYTE i_code; /* type sub code */
USHORT i_cksum;
USHORT i_id;
USHORT i_seq;
/* This is not the std header, but we reserve space for time */
ULONG timestamp;
}IcmpHeader;

#define STATUS_FAILED 0xFFFF
#define DEF_PACKET_SIZE 32
#define MAX_PACKET 1024

#define xmalloc(s) HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,(s))
#define xfree(p) HeapFree (GetProcessHeap(),0,(p))

void fill_icmp_data(char *, int);
USHORT checksum(USHORT *, int);
void decode_resp(char *,int ,struct sockaddr_in *);

void Usage(char *progname){

fprintf(stderr,"Usage:\n");
fprintf(stderr,"%s <host> [data_size]\n",progname);
fprintf(stderr,"datasize can be up to 1Kb\n");
ExitProcess(STATUS_FAILED);

}
int main(int argc, char **argv){

WSADATA wsaData;
SOCKET sockRaw;
struct sockaddr_in dest,from;
struct hostent * hp;
int bread,datasize;
int fromlen = sizeof(from);
int timeout = 1000;
char *dest_ip;
char *icmp_data;
char *recvbuf;
unsigned int addr=0;
USHORT seq_no = 0;

if (WSAStartup(MAKEWORD(2,1),&wsaData) != 0){
fprintf(stderr,"WSAStartup failed: %d\n",GetLastError());
ExitProcess(STATUS_FAILED);
}

if (argc <2 ) {
Usage(argv[0]);
}
sockRaw = WSASocket (AF_INET,
SOCK_RAW,
IPPROTO_ICMP,
NULL, 0,0);

if (sockRaw == INVALID_SOCKET) {
fprintf(stderr,"WSASocket() failed: %d\n",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
bread = setsockopt(sockRaw,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,
sizeof(timeout));
if(bread == SOCKET_ERROR) {
fprintf(stderr,"failed to set recv timeout: %d\n",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
timeout = 1000;
bread = setsockopt(sockRaw,SOL_SOCKET,SO_SNDTIMEO,(char*)&timeout,
sizeof(timeout));
if(bread == SOCKET_ERROR) {
fprintf(stderr,"failed to set send timeout: %d\n",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
memset(&dest,0,sizeof(dest));

hp = gethostbyname(argv[1]);

if (!hp){
addr = inet_addr(argv[1]);
}
if ((!hp) && (addr == INADDR_NONE) ) {
fprintf(stderr,"Unable to resolve %s\n",argv[1]);
ExitProcess(STATUS_FAILED);
}

if (hp != NULL)
memcpy(&(dest.sin_addr),hp->h_addr,hp->h_length);
else
dest.sin_addr.s_addr = addr;

if (hp)
dest.sin_family = hp->h_addrtype;
else
dest.sin_family = AF_INET;

dest_ip = inet_ntoa(dest.sin_addr);

if (argc >2) {
datasize = atoi(argv[2]);
if (datasize == 0)
datasize = DEF_PACKET_SIZE;

}
else
datasize = DEF_PACKET_SIZE;

datasize += sizeof(IcmpHeader);

icmp_data = xmalloc(MAX_PACKET);
recvbuf = xmalloc(MAX_PACKET);

if (!icmp_data) {
fprintf(stderr,"HeapAlloc failed %d\n",GetLastError());
ExitProcess(STATUS_FAILED);
}

memset(icmp_data,0,MAX_PACKET);
fill_icmp_data(icmp_data,datasize);

while(1) {
int bwrote;

((IcmpHeader*)icmp_data)->i_cksum = 0;
((IcmpHeader*)icmp_data)->timestamp = GetTickCount();

((IcmpHeader*)icmp_data)->i_seq = seq_no++;
((IcmpHeader*)icmp_data)->i_cksum = checksum((USHORT*)icmp_data,
datasize);

bwrote = sendto(sockRaw,icmp_data,datasize,0,(struct sockaddr*)&dest,
sizeof(dest));
if (bwrote == SOCKET_ERROR){
if (WSAGetLastError() == WSAETIMEDOUT) {
printf("timed out\n");
continue;
}
fprintf(stderr,"sendto failed: %d\n",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
if (bwrote < datasize ) {
fprintf(stdout,"Wrote %d bytes\n",bwrote);
}
bread = recvfrom(sockRaw,recvbuf,MAX_PACKET,0,(struct sockaddr*)&from,
&fromlen);
if (bread == SOCKET_ERROR){
if (WSAGetLastError() == WSAETIMEDOUT) {
printf("timed out\n");
continue;
}
fprintf(stderr,"recvfrom failed: %d\n",WSAGetLastError());
ExitProcess(STATUS_FAILED);
}
decode_resp(recvbuf,bread,&from);
Sleep(1000);

}
return 0;

}
/*
The response is an IP packet. We must decode the IP header to locate
the ICMP data
*/
void decode_resp(char *buf, int bytes,struct sockaddr_in *from) {

IpHeader *iphdr;
IcmpHeader *icmphdr;
unsigned short iphdrlen;

iphdr = (IpHeader *)buf;

iphdrlen = iphdr->h_len * 4 ; // number of 32-bit words *4 = bytes

if (bytes < iphdrlen + ICMP_MIN) {
printf("Too few bytes from %s\n",inet_ntoa(from->sin_addr));
}

icmphdr = (IcmpHeader*)(buf + iphdrlen);

if (icmphdr->i_type != ICMP_ECHOREPLY) {
fprintf(stderr,"non-echo type %d recvd\n",icmphdr->i_type);
return;
}
if (icmphdr->i_id != (USHORT)GetCurrentProcessId()) {
fprintf(stderr,"someone else's packet!\n");
return ;
}
printf("%d bytes from %s:",bytes, inet_ntoa(from->sin_addr));
printf(" icmp_seq = %d. ",icmphdr->i_seq);
printf(" time: %d ms ",GetTickCount()-icmphdr->timestamp);
printf("\n");

}

USHORT checksum(USHORT *buffer, int size) {

unsigned long cksum=0;

while(size >1) {
cksum+=*buffer++;
size -=sizeof(USHORT);
}

if(size ) {
cksum += *(UCHAR*)buffer;
}

cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >>16);
return (USHORT)(~cksum);
}
/*
Helper function to fill in various stuff in our ICMP request.
*/
void fill_icmp_data(char * icmp_data, int datasize){

IcmpHeader *icmp_hdr;
char *datapart;

icmp_hdr = (IcmpHeader*)icmp_data;

icmp_hdr->i_type = ICMP_ECHO;
icmp_hdr->i_code = 0;
icmp_hdr->i_id = (USHORT)GetCurrentProcessId();
icmp_hdr->i_cksum = 0;
icmp_hdr->i_seq = 0;

datapart = icmp_data + sizeof(IcmpHeader);
//
// Place some junk in the buffer.
//
memset(datapart,'E', datasize - sizeof(IcmpHeader));

}

F. 1.linux系統下shell腳本用case語句編寫四則運算 2.linux系統下shell腳本輸入數字串。進行反序輸出

如果只做四個簡單的運算這應應該可以

shell腳本代碼如下:
#!/bin/bash
read -p "input num1:" a
read -p "input num2:" b
read -p "input operator:" o
case $o in
+) let "res=a + b"
echo $res;;
-) let "res=a - b"
echo $res;;
/) awk 'BEGIN{printf "%.2f\n",'$a'/'$b'}';;
*) let "res=a * b"
echo $res;;
esac

G. sar命令查看歷史數據

前言

有的時候,我們要通過對系統的cpu負載等性能數值的查看,來判排查系統產生某種故障(經常死機或者運行速度突然變慢)的原因。但是,簡單的top,uptime,w等命令只可以查看當前的負載,而無法查看過去的某一時間段的cpu的負載情況。

下面就介紹一個用於性能分析的命令,其可以用於查看過去的某一時間段的cpu的負載情況(系統性能)。

查看某一時間段的cpu使用情況,請直接跳到第七節。

一、sar概念

sysstat是Linux 系統中的常用工具包,而sar 是 Linux中sysstat工具包中的用於監控Linux系統性能的工具之一。

sysstat 工具包中包含兩種類型的工具:即時查看工具(iostat、mpstat、sar);累計統計工具(sar)

因此sar命令,又叫做系統活動情況報告。不僅可以實時查看伺服器的性能,還可以做累計統計。

二、sar可監控的范圍

文件的讀寫情況

系統調用的使用情況

磁碟I/O使用情況

CPU的使用統計

內存使用狀況

進程活動

IPC有關的活動

三、sar命令使用環境

sar命令使用格式:

sar+ 命令行選項(可選) + 間隔時間(可選) + 次數(可選)

常用來判斷一個系統瓶頸問題

查詢CPU可用 sar -u 和 sar -q 等來查看查詢內存可用 sar -B、sar -r 和 sar -W 等來查看查詢io可用 sar -b、sar -u 和 sar -d 等來查看

四、sar命令累計統計的實現過程

系統會通過調用 /usr/lib64/sa/ 中的三個工具(sa1 sa2 sadc)來實現,周期地記錄當時的系統性能的信息的功能。

sa1 :收集並將每天的系統性能的信息寫入一個二進制的文件中,它是sadc的前端程序

sa2 :收集每天的系統活躍的信息並寫入總結性的文件中,其作為 sar的前端程序

sadc :收集系統的動態數據的數據並寫入一個二進制的文件中,其作為 sar 工具的後端

五、sar的日誌

sar是由有類似日誌切割的功能的,它會依據/etc/cron.d/sysstat中的計劃任務,將日誌放入/var/log/sa/中

註:日誌為二進制文件,不可使用more、less、vim工具查看,必須使用sar或sadf

可以根據需求修改該計劃任務

如要查看某一時間段的伺服器的性能的其中一個方法就是:使用sar命令,查看當天的日誌文件

sar -f /var/log/sa/sa15

[root@    lib64]#sar-f/var/log/sa/sa15Linux3.10.0-327.el7.x86_64(ops-node7)07/15/2018_x86_64_(24CPU)12:00:01AMCPU%user%nice%system%iowait%steal%idle12:10:01AMall1.350.000.850.120.0097.6712:20:01AMall1.320.000.860.110.0097.7112:30:02AMall1.370.000.870.110.0097.6512:40:01AMall1.320.000.910.110.0097.6612:50:01AMall1.350.000.890.110.0097.6501:00:01AMall1.360.000.870.110.0097.6601:10:01AMall1.360.000.850.110.0097.6801:20:01AMall1.350.000.890.100.0097.6601:30:01AMall1.320.000.890.110.0097.6801:40:01AMall1.290.000.950.110.0097.6501:50:01AMall1.350.000.880.120.0097.6402:00:01AMall1.340.000.880.110.0097.6802:10:01AMall1.330.000.900.110.0097.6502:20:01AMall1.360.000.870.120.0097.6502:30:01AMall1.350.000.850.120.0097.6802:40:01AMall1.410.000.920.120.0097.5602:50:01AMall1.570.000.950.130.0097.3503:00:01AMall4.210.000.810.160.0094.8103:10:01AMall2.500.000.870.130.0096.5003:20:01AMall1.370.000.870.120.0097.6503:30:01AMall1.360.000.950.130.0097.5603:40:01AMall1.480.000.970.240.0097.3003:50:01AMall1.350.010.910.130.0097.6004:00:01AMall1.390.000.950.190.0097.4704:10:01AMall1.360.000.990.130.0097.52

注意:

sar查看性能或其日誌時,使用的12/24小時制;日誌的切割是昨天晚上12點到今天12點為一天;默認只保留一個月的日誌

六、sar命令參數及輸出項詳解

【1】格式

用法:sar + 選項 + 時間間隔(可選) + 次數 (可選)

interval: 取樣周期,單位是秒count:取樣次數,默認值為1options:命令行選項

【2】常用選項

-A          所有報告的總和-B          輸出內存頁面的統計信息-b          輸出I/O和傳送速率的統計信息-C          輸出進程統計信息及每秒創建的進程數-d          輸出每一個塊設備的活動信息-H          輸出交換空間利用率信息-h          輸出幫助信息-p          輸出友好設備名字,以方便查看,常與-d和-n參數結合使用-q          輸出進程隊列長度和系統平均負載狀態統計信息-R          輸出內存頁面的統計信息-r          輸出內存和交換空間的統計信息-S          輸出交換空間利用率信息-t          讀取 /var/log/sa/下的某日誌的數據時顯示其中記錄的原始時間-u          輸出整體CPU使用情況的統計信息-V          輸出版本信息-v          輸出內核表狀況統計信息(inode、文件和其他內核表的統計信息)-W          輸出系統交換的統計信息-w          輸出任務創建與系統轉換統計信息-y          輸出終端設備的活動信息-----------I          輸出指定中斷的統計信息,後方可加參數{...|SUM|ALL|XALL}  ...          指定中斷號SUM          指定輸出每秒接收到的中斷總數ALL          指定輸出前16個中斷XALL        指定輸出全部的中斷信息-----------P          輸出指定的部分的CPU的統計信息,後方可加參數{cpu|ALL}cpu          指定cpuALL          輸出單個和整體cpu的統計數據-----------n          輸出網路設備(網卡)狀態統計信息,後方可加參數{DEV|EDEV|NFS|NFSD|SOCK|ALL}    DEV          輸出網路設備的統計信息EDEV        輸出網路設備的錯誤統計信息NFS          輸出NFS客戶端的活動統計信息NFSD        輸出NFS伺服器的活動統計信息SOCK        輸出網路套接字的使用統計信息ALL          輸出所有類型的網路活動統計信息-----------f          從文件中讀取數據信息。一般讀取sar日誌,也可讀取-o選項生成的文件,後方要加文件名-o          將sar的輸出信息保存到文件中,後方要加文件名-i          指定間隔時長,單位為秒-s          指定輸出統計數據的起始時間(格式為hh:mm:ss;例如01:00:00)  -e          指定輸出統計數據的截至時間,通常與-S選項連用。無數值時默認為18:00:00(格式為hh:mm:ss;例如09:00:00)

【3】輸出項

<1>cpu的輸出

sar -u

%usr              CPU在用戶模式下,執行進程的時間百分比 %nice              CPU在用戶模式下,用於nice操作,所佔用CPU總時間的百分比 %system            CPU處在系統模式(內核態)下,執行進程的時間百分比 %iowait            CPU用於等待I/O操作完成(等待輸入輸出完成),佔用CPU總時間的百分比 %steal            管理程序為另一個虛擬進程提供服務而等待虛擬CPU的百分比%idle              CPU空閑時間百分比

注意:

如果%iowait的值過高,表示硬碟存在I/O瓶頸 如果%idle值高,表示CPU較空閑如果%idle 的值高但系統響應慢時,有可能是 CPU 等待分配內存,此時應加大內存容量 如果%idle 的值持續低於10,則系統的 CPU 處理能力相對較低,表明系統中最需要解決的資源是 CPU

<2>I/O和傳送速率輸出

sar -b

tps                每秒向磁碟設備請求數據的次數,包括讀、寫請求,其為rtps與wtps的和。每一次IO下發後會先將多個請求合並為一個I/O磁碟請求,這里tps指請求合並後的請求計數rtps              每秒向磁碟設備的讀請求次數 wtps              每秒向磁碟設備的寫請求次數 bread/s            每秒鍾從物理設備讀入的數據量,單位為 塊/s bwrtn/s            每秒鍾向物理設備寫入的數據量,單位為 塊/s

<3>設備使用情況輸出

sar -d

DEV                磁碟設備,加上用參數-p可以列印出sda等磁碟設備名稱;如不加參數-p,設備則顯示為dev253-0等tps                每秒向磁碟設備請求數據的次數,包括讀、寫請求,其為rtps與wtps的和。每一次IO下發後會先將多個請求合並為一個I/O磁碟請求,這里tps指請求合並後的請求計數rd_sec/s          每秒讀扇區的次數wr_sec/s          每秒寫扇區的次數avgrq-sz          平均每次設備I/O操作的數據大小(扇區)avgqu-sz          磁碟請求隊列的平均長度await              從請求磁碟到系統處理完,每次請求的平均消耗時間,包括請求隊列等待時間(單位是毫秒)svctm              系統處理每次請求的平均時間,不包括在請求隊列中消耗的時間%util              I/O請求佔CPU的百分比

<4>網路設備統計信息輸出

sar -n EDEV

IFACE              網路設備名rxpck/s            每秒接收的包數量txpck/s            每秒傳輸的包數量rxbyt/s            每秒接收的位元組數(單位為byte)txbyt/s            每秒傳輸的位元組數(單位為byte)rxkB/s            每秒收的數據量(單位為kB)txkB/s            每秒發的數據量(單位為kB)rxcmp/s            每秒接收壓縮包的數量txcmp/s            每秒傳輸壓縮包的數量rxmcst/s          每秒接收的多播(multicast)包的總數排查網路設備故障

<5>網路設備故障信息輸出

EDEV |egrep 『eth0|IFACE』 (本次指定了網卡etho0,可填入其他網卡)

IFACE網路設備名rxerr/s每秒接收的壞包數量txerr/s傳輸包時每秒發生錯誤的數量coll/s傳輸包時每秒發生沖突的數量rxdrop/s接收包時,每秒丟棄的包的數量(缺乏緩存導致)txdrop/s傳輸包時,每秒丟棄的包的數量(缺乏緩存導致)txcarr/s傳輸包時,每秒發生的傳輸錯誤的數量rxfram/s接收包時,每秒發生幀校驗錯誤的數量rxfifo/s接收包時,每秒鍾緩沖區溢出錯誤的數量txfifo/s傳輸包時,每秒鍾緩沖區溢出錯誤的數量

<6>內存分頁狀態輸出

sar -B

pgpgin/s每秒從磁碟空間或交換空間置換到內存的位元組數(單位為KB)pgpgout/s每秒從內存置換到磁碟空間或交換空間的位元組數(單位為KB)fault/s每秒鍾系統產生的缺頁數(主缺頁加次缺頁)majflt/s每秒鍾產生的主缺頁數pgfree/s每秒被放入空閑隊列中的頁個數pgscank/s每秒被kswapd掃描的頁個數pgscand/s每秒直接被掃描的頁個數pgsteal/s每秒鍾從cache中被清除來滿足內存需要的頁個數%vmeff每秒清除的頁占總掃描頁的百分比

<7>進程隊列長度和平均負載狀態輸出

sar -q

runq-sz          運行隊列的長度,等待運行的進程數量

plist-sz        進程列表中進程和線程的數量

ldavg-1          最後1分鍾的系統平均負載

ldavg-5          過去5分鍾的系統平均負載

ldavg-15        過去15分鍾的系統平均負載

<8>內存和交換空間狀態輸出

sar -r

kbmemfree空閑的內存數量(單位為KB)kbmemused已使用的內存數量,不包含內核使用的內存(單位為KB)%memused已使用內存的百分數kbbuffers內核緩沖區buffer,使用的內存數量(單位為KB)kbcached內核高速緩存cache數據使用的內存數量(單位為KB)kbcommit保證當前系統所需要的內存,即為了確保不溢出而需要的內存(RAM+swap)%commitkbcommit與所有內存總量的百分比

<9>系統交換活動信息輸出

sar -W

pswpin/s          每秒系統換入的交換頁面數量

pswpout/s          每秒系統換出的交換頁面數量

七、sar使用實例-查看某一時間段的情況

<1>查看凌晨1點到3點的cpu

sar -s 01:00:00 -e 03:00:00

<2>查看凌晨1點到3點的系統的平均負載

若要看某時間段其他性能,加上對應選項

sar -s 01:00:00 -e 03:00:00 -q

<3>查看本月3號的cpu

注意:

該操作需要去查看sar的日誌(第五節已經介紹一次)

默認只保存一個月的

sar查看性能或其日誌時,注意自己的使用的是12還是24小時制

日誌的切割是昨天晚上12點到今天12點為一天

cd/var/log/sa/sar -f sa03

H. LINUX的SHELL腳本,有關添加和刪除用戶腳本

#!/bin/bash

read -p "請輸入用戶前綴: " A
read -p "悉此請輸入刪除用戶起始范圍: " B
read -p "請輸入睜歲迅雀旦刪除用戶結束范圍: " C

while [ $B -le $C ]
do
if [ $B -lt 10 ]
then
USE=0$B
else
USE=$B
fi
userdel $A$USE
let B++
done

I. 來解決裝linux的問題

你需要有Grub for dos。啟動dos,進入grub,然後使用grub引導安裝。
一下是硬碟安裝SUSE的參考
A:\>M:
M:\>cd grub --(假滲缺設你的grub放在M:\grub\)
M:\grub>grub
GRUB>root(hd0,0) --(指定啟動漏逗磁碟和磁碟分區)
GRUB>kernel \loader\Linux vga=791 --(指定啟動文件位置,並設置屏叢搜辯幕模式為791--1024*768)
GRUB>initrd \loader\initrd --(指定initrd.img位置)
GRUB>boot

J. Linux裡面block代表什麼意思

在2.4 的 fs/buffers.c 的函數
static int __block_prepare_write(struct inode *inode, struct page *page,
unsigned from, unsigned to, get_block_t *get_block)

中有如下代碼:

if (!page->buffers)
create_empty_buffers(page, inode->i_dev, blocksize);
head = page->buffers;

bbits = inode->i_sb->s_blocksize_bits;
block = page->index << (PAGE_CACHE_SHIFT - bbits);

for(bh = head, block_start = 0; bh != head || !block_start;
block++, block_start=block_end, bh = bh->b_this_page) {
if (!bh)
BUG();
block_end = block_start+blocksize;
if (block_end <= from)
continue;
if (block_start >= to)
break;
if (!buffer_mapped(bh)) {
err = get_block(inode, block, bh, 1);
if (err)
goto out;
if (buffer_new(bh)) {
unmap_underlying_metadata(bh);
if (Page_Uptodate(page)) {
set_bit(BH_Uptodate, &bh->b_state);
continue;
}
if (block_end > to)
memset(kaddr+to, 0, block_end-to);
if (block_start < from)
memset(kaddr+block_start, 0, from-block_start);
if (block_end > to || block_start < from)
flush_dcache_page(page);
continue;
}
}

對unmap_underlying_metadata 的意義不是特別明確, 注釋說是釋放潛在的bh. 實現是從hash中找到bh代表的設備上, bh-->blocknr 那個塊的oldbh, 如果有的話把它釋放.
奇怪的是,既然是新分配的,為什麼慎雹在hash中能找到? 如宏孝察果hash中本來就有, 需要蔽茄新分配嗎?

/*
* We are taking a block for data and we don't want any output from any
* buffer-cache aliases starting from return from that function and
* until the moment when something will explicitly mark the buffer
* dirty (hopefully that will not happen until we will free that block ;-)
* We don't even need to mark it not-uptodate - nobody can expect
* anything from a newly allocated buffer anyway. We used to used
* unmap_buffer() for such invalidation, but that was wrong. We definitely
* don't want to mark the alias unmapped, for example - it would confuse
* anyone who might pick it with bread() afterwards...
*/

static void unmap_underlying_metadata(struct buffer_head * bh)
{
struct buffer_head *old_bh;

old_bh = get_hash_table(bh->b_dev, bh->b_blocknr, bh->b_size);
if (old_bh) {
mark_buffer_clean(old_bh);
wait_on_buffer(old_bh);
clear_bit(BH_Req, &old_bh->b_state);
/* Here we could run brelse or bforget. We use
bforget because it will try to put the buffer
in the freelist. */
__bforget(old_bh);
}
}

閱讀全文

與linuxbread相關的資料

熱點內容
webbrowser密碼框 瀏覽:720
大奶按摩電影 瀏覽:126
nios2uclinux文件系統 瀏覽:228
拍攝指南by製造機txt下載 瀏覽:187
中東一個小男孩的電影 瀏覽:41
最好看的機甲小說 瀏覽:495
小孩第一次進電影院英文翻譯 瀏覽:729
ios獲取項目文件路徑 瀏覽:100
色武俠小說 瀏覽:879
users文件夾共享 瀏覽:372
mybatis查詢大數據 瀏覽:278
染島貢電影 瀏覽:101
蘋果7黑屏指紋沒反應 瀏覽:655
如何把相冊轉成文件 瀏覽:973
pb這么獲取資料庫窗口的值 瀏覽:856
數據類型中哪些支持默認約束 瀏覽:711
裸眼3D電影左右格式下載 瀏覽:848
如何通過網路線控制連接主機 瀏覽:873
韓劇海嘯電影 瀏覽:231
韓國電影男孩在樓上偷看樓下 瀏覽:151

友情鏈接