Sunteți pe pagina 1din 12

Hệ điều hành – Bài tập Tuần 2 : PROCESS 1

Tạo và quản lý tiến trình


Bài tập 1 :
Xem thông tin về tiến trình, trong Linux ta có thể dùng lệnh ps , top . Trong Windows , ta có
công cụ Task Manager.

Sử dụng các công cụ trên để xem thông tin về tiến trình ?

Tham khảo hướng dẫn sau :

Lệnh ps

1. Run ps without any options

This is a very basic ps usage. Just type ps on your console to see its result.

By default, it will show us 4 columns of information.

• PID is a Process ID of the running command (CMD)


• TTY is a place where the running command runs
• TIME tell about how much time is used by CPU while running the command
• CMD is a command that run as current process
This information is displayed in unsorted result.

2. Show all current processes

To do this, we can use -a options. As we can guess, -a is stand for “all”. While x will show all
process even the current process is not associated with any TTY (terminal)

$ ps -ax

This result might be long result. To make it more easier to read, combine it with less command.

$ ps -ax | less

3. Filter processes by its user

For some situation we may want to filter processes by user. To do this, we can use -u option. Let
say we want to see what processes which run by user pungki. So the command will be like below

$ ps -u pungki

4. Filter processes by CPU or memory usage

1
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 2

Another thing that you might want to see is filter the result by CPU or memory usage. With this, you
can grab information about which processes that consume your resource. To do this, we can
use aux options. Here’s an example of it :

$ ps -aux | less

Since the result can be in a long list, we can pipe less command into ps command.
By default, the result will be in unsorted form. If we want to sort by particular column, we can add --
sortoption into ps command.

Sort by the highest CPU utilization in ascending order

$ ps -aux --sort -pcpu | less

Sort by the highest Memory utilization in ascending order

$ ps -aux --sort -pmem | less

Or we can combine itu a single command and display only the top ten of the result :

$ ps -aux --sort -pcpu,+pmem | head -n 10

5. Filter processes by its name or process ID

To to this, we can use -C option followed by the keyword. Let say, we want to show processes
named getty. We can type :

$ ps -C getty

If we want to show more detail about the result, we can add -f option to show it on full format listing.
The above command will looks like below :

$ ps -f -C getty

6. Filter processes by thread of process

If we need to know the thread of a particular process, we can use -L option followed by its Process
ID (PID). Here’s an example of -L option in action :

$ ps -L 1213

As we can see, the PID remain the same value, but the LWP which shows numbers of thread show
different values.

7. Show processes in hierarchy

Sometime we want to see the processes in hierarchical form. To do this, we can use -axjf options.

2
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 3

$ps -axjf

Or, another command which we can use is pstree.

$ pstree

8. Show security information

If we want to see who is currently logged on into your server, we can see it using the ps command.
There are some options that we can use to fulfill our needs. Here’s some examples :

$ ps -eo pid,user,args

Option -e will show you all processes while -o option will control the output. Pid, User and
Args will show you the Process ID, the User who run the application and the running
application.

The keyword / user-defined format that can be used with -e option are args, cmd, comm,
command, fname, ucmd, ucomm, lstart, bsdstart and start.

9. Show every process running as root (real & effecitve ID) in user format

System admin may want to see what processes are being run by root and other information related
to it. Using ps command, we can do by this simple command :

$ ps -U root -u root u

The -U parameter will select by real user ID (RUID). It selects the processes whose real user name
or ID is in the userlist list. The real User ID identifies the user who created the process.

While the -u paramater will select by effective user ID (EUID)

The last u paramater, will display the output in user-oriented format which contains User, PID,
%CPU, %MEM, VSZ, RSS, TTY, STAT, START, TIME and COMMAND columns.

10. Use PS in a realtime process viewer

ps will display a report of what happens in your system. The result will be a static report.
Let say, we want to filter processes by CPU and Memory usage as on the point 4 above. And we
want the report is updated every 1 second. We can do it by combining ps command with watch
command on Linux.

Here’s the command :

$ watch -n 1 ‘ps -aux --sort -pmem, -pcpu’

3
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 4

If you feel the report is too long, we can limit it by - let say - the top 20 processes. We can
add headcommand to do it.

$ watch -n 1 ‘ps -aux --sort -pmem, -pcpu | head 20’

This live reporter is not like top or htop of course. But the advantage of using ps to make live
report is that you can custom the field. You can choose which field you want to see.

For example, if you need only the pungki user shown, then you can change the command to
become like this :

$ watch -n 1 ‘ps -aux -U pungki u --sort -pmem, -pcpu | head 20’

(http://linoxide.com/how-tos/linux-ps-command-examples/)

Lệnh top

1. Display of Top Command

In this example, it will show information like tasks, memory, cpu and swap. Press ‘q‘ to quit
window.
$ top

2. Sorting with -O (Uppercase Letter ‘O’).

Press (Shift+O) to Sort field via field letter, for example press ‘a‘ letter to sort process with PID
(Process ID).
Type any key to return to main top window with sorted PID order as shown in below screen.
Press ‘q‘ to quit exit the window.

3. Display Specific User Process

Use top command with ‘u‘ option will display specific User process details.
$ top –u <username>

4. Highlight Running Process in Top

Press ‘z‘ option in running top command will display running process in color which may help
you to identified running process easily.

5. Shows Absolute Path of Processes

4
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 5

Press ‘c‘ option in running top command, it will display absolute path of running process.

6. Change Delay or Set ‘Screen Refresh Interval’ in Top

By default screen refresh interval is 3.0 seconds, same can be change pressing ‘d‘ option in
running top command and change it as desired as shown below.

7. Kill running process with argument ‘k’

You can kill a process after finding PID of process by pressing ‘k‘ option in running top
command without exiting from top window as shown below.

8. Sort by CPU Utilisation

Press (Shift+P) to sort processes as per CPU utilization. See screenshot below.

9. Renice a Process

You can use ‘r‘ option to change the priority of the process also called Renice.

10. Save Top Command Results

Press (Shift+W) to save the running top command results under /root/.toprc.

11. Getting Top Command Help

Press ‘h‘ option to obtain the top command help.

12. Exit Top Command After Specific repetition

Top output keep refreshing until you press ‘q‘. With below command top command will
automatically exit after 10 number of repetition.
top –n 10
There are number of arguments to know more about top command you may refer man page
of top command. Please share it if you find this article useful through our comment box below.

5
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 6

Bài tập 2 : Tạo tiến trình bằng fork() system call


o Fork() system call cho phép một tiến trình (parent) tạo một tiến trình mới (child). Fork() tạo tiến
trình con bằng cách sao chép không gian địa chỉ của tiến trình cha : tiến trình con chứa bản copy
các stack , data, heap, text segment của tiến trình cha.
Sau khi tiến trình con được tạo, Cả 2 tiến trình sẽ bắt đầu thực thi từ câu lệnh kế tiếp lời gọi
fork() .
o Hàm fork() trả về giá trị :
▪ nếu tạo tiến trình con không thành công : -1
▪ nếu tạo tiến trình con thành công : fork() trả về 0 cho tiến trình con , và trả về PID của
tiến trình con cho tiến trình cha
Tham khảo : man fork

Chương trình fork01.c : phân biệt xử lý tiến trình cha-con bằng sử dụng cấu trúc if-else
hoặc switch-case . Hãy đọc hiểu chương trình, thực thi và xem kết quả ?

6
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 7

Bài tập 3 : Tạo tiến trình bằng fork() system call (tiếp theo)
Chương trình fork02.c : Kết xuất của hai tiến trình đan xen nhau , phụ thuộc vào bộ
lập lịch. Hãy đọc hiểu chương trình, thực thi và xem kết quả ?

Hoặc, sử dụng sleep() để cho phép tiến trình con thực thi và có thể hoàn thành tác vụ
trước tiến trình cha:

7
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 8

Bài tập 4 : Thực thi chương trình


execve() system call nạp một chương trình mới vào vùng nhớ của process hiện hành. Các text,
data, stack segment của process hiện hành được thay thế bởi thành phần tương ứng của
chương trình mới.

Cách dùng thông dụng nhất của execve() là ở trong tiến trình con được sinh bởi một fork (), mặc
dù nó cũng thỉnh thoảng được sử dụng trong các ứng dụng mà không có fork() .

#include <unistd.h>
int execve(const char *pathname, char *const argv[], char *const envp[]);
Never returns on success; returns –1 on error
- pathname: tên đường dẫn của chương trình mới. Đường dẫn này có thể là tuyệt đối hoặc tương
đối - liên quan đến thư mục làm việc hiện tại của process gọi.
argv : chỉ định các đối số dòng lệnh truyền cho chương trình mới. Là một mảng con trỏ kết thúc
bằng NULL, trỏ tới chuỗi ký tự. Giá trị cung cấp cho argv [0] tương ứng với tên lệnh.
envp: chỉ định danh sách môi trường cho chương trình mới. envp argument tương ứng với
environ array của chương trình mới; nó là một danh sách con trỏ NULL-teminated dạng chuỗi :
có cấu trúc name = value .

- Có nhiều hàm exec, là các API của system call execve(). Mỗi hàm có một giao diện khác nhau,
nhưng chức năng tương tự :

8
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 9

Tham khảo : man execve , man exec.

Chương trình fork03.c : thực thi một chương trình. Đọc hiểu chương trình , thực thi và xem
kết quả ?

9
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 10

Bài tập 5 : Kết thúc một tiến trình và trạng thái kết thúc - exit() và wait()
Hàm thư viện exit(status) kết thúc một tiến trình, tất cả các tài nguyên (memory, open file
descriptors, …) đang được sử dụng bởi tiến trình sẵn sàng cho kernel phân bổ lại cho các tiến
trình khác. Tham số status là một số nguyên xác định trạng thái kết thúc của tiến trình. Sử dụng
lời gọi hệ thống wait() để có thể nhận tham số status này. (Tham khảo thêm _exit() system call )

Lời gọi hệ thống wait(&status) có hai mục đích : thứ nhất, tiến trình cha tạm dừng cho đến khi
một trong các tiến trình con của nó kết thúc (bằng exit(), … ). Thứ hai, trạng thái kết thúc của
tiến trình con được trả về trong tham số status của wait().

Có thể thông dịch thông tin về trạng thái kết thúc của tiến trình con sử dụng các macro định
nghĩa trong sys/wait.h :

WIFEXITED(stat_val) Nonzero if the child is terminated normally.


WEXITSTATUS(stat_val) If WIFEXITED is nonzero, this returns child exit code.
WIFSIGNALED(stat_val) Nonzero if the child is terminated on an uncaught signal.
WTERMSIG(stat_val) If WIFSIGNALED is nonzero, this returns a signal number.
WIFSTOPPED(stat_val) Nonzero if the child has stopped.
WSTOPSIG(stat_val) If WIFSTOPPED is nonzero, this returns a signal number.

Tham khảo : man exit , man wait, man waitpid

10
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 11

Chương trình fork04.c : nhận trạng thái trả về của tiến trình con.

Đọc hiểu chương trình, thực thi và xem kết quả ?

11
NH&TT biên soạn (2016)
Hệ điều hành – Bài tập Tuần 2 : PROCESS 12

Bài tập ứng dụng :


1. Zombie process
Khi một tiến trình con kết thúc, thông tin về nó vẫn còn tồn tại trong hệ thống (trong process
table) đến khi tiến trình cha kết thúc hoặc gọi hàm wait. Tiến trình con lúc này được gọi là
zombie process ( hay defunct ).
Viết chương trình minh họa sự tồn tại của một Zombie process ?

12
NH&TT biên soạn (2016)

S-ar putea să vă placă și