Professional Documents
Culture Documents
OSLab 2
OSLab 2
- phn 2 -
Ni dung
Bin dch v thc thi chng trnh C/C++
Gii thiu v process
T chc ca mt process
Background v foreground process
Cc lnh thao tc vi process
Qu trnh to process
gas/gcc/g++
gcc/g++
.o
Ba bc 1, 2, 3 ch yu lm vic vi mt file u vo
Bc 4 c th lin kt nhiu object module lin quan to
thnh file thc thi nh phn (executable binary)
Lp trnh vin c th can thip vo tng bc trn
preprocessed
source files
hello.cpp
.cpp
.s
gcc -x assembler -c hello.s [-o hello.o]
object
code
hello.o
b.o
a.o
a.out/hello
Khoa Cng ngh
ngh Thng tin -
i h
hc B
Bch Khoa Tp. HCM
2.6
Tm tt mt s ty chn ca gcc
Ty chn
Cng dng
-o FILE
Ch nh tn ca file output (khi bin dch thnh file thc thi, nu khng
c -o filename th tn file mc nh s l a.out)
-c
-IDIRNAME
-LDIRNAME
-O [n]
-g
-E
-S
-lfoo
-ansi
Bin dch theo chun ANSI C/C++ (s cnh bo nu code khng chun)
Khoa Cng ngh
ngh Thng tin -
i h
hc B
Bch Khoa Tp. HCM
2.7
#include "reciprocal.h"
double reciprocal (int i) {
assert (i != 0);
return 1.0/i;
}
statically
linking
dynamically
linking
Libraries
Libraries
b.c
int func1(){
double func2(){
return 7;
return 3.14159;
}
Khoa Cng ngh
ngh Thng tin -
i h
hc B
Bch Khoa Tp. HCM
2.15
$ nm libab.a
4. C th dng lnh file xem file libab.a l loi file g
$ file libab.a
$ file libab.so
libab.so: ELF 32-bit LSB shared object, Intel 80386, version 1
(SYSV), not stripped
Khoa Cng ngh
ngh Thng tin -
i h
hc B
Bch Khoa Tp. HCM
2.18
C bn v PROCESS
Process: chng trnh ang thc thi.
User c th theo di trng thi ca process, tng tc
vi process
C hai loi user process ch yu trong h thng
Foreground process
Background process
Theo di cc process
Xem trng thi cc process (process status)
ps [option]
Options
-e
chn tt cc process
-f
-A
lit k tt c processs
V d
$ find / *.profile -print
...
^Z
[1]+
Stopped
find / ".profile"
$ps
PID TTY
TIME CMD
2750 pts/1
00:00:00 bash
2881 pts/1
00:00:00 find
2883 pts/1
00:00:00 ps
Stopped
$ fg 1
hoc
$ bg 1
[1] 2548
i vi cc qu trnh, c th:
C th chuyn process t thc thi background sang foreground
v ngc li dng lnh fg hoc bg
Kt thc mt qu trnh (~ mt job)
$ls R / > kq
...
^Z
[1]+
$bg
Stopped
ls R / >kq
Running
ls -R / >kq &
$ fg 1
Kt thc qu trnh
Dng lnh kill
kill [-signal] process_identifier (PID)
-9
or
process_identifier
Lp trnh PROCESS
Kin trc h thng *NIX
T chc ca process
X l tham s dng lnh (command line arguments)
To mi v kt thc process
Gi thc thi lnh/chng trnh khc bng system(),
exec()
S lc v *NIX
n khi (monolithic)
a nhim (multitasking)
Nhiu ngi dng ng thi (multiuser)
a dng (general purpose)
Chia s thi gian (time-sharing)
Bo mt
ng dng
Giao din lp
trnh
Nhn (kernel)
Phn cng
(the users)
Shell and commands
Compilers & Interpreters
System libraries
Signals
Termial handling
Character I/O system
Terminal drivers
File system
Swapping
Block I/O system
Disk & tape drivers
CPU scheduling
Page replacement
Demand paging
Virtual memory
Terminal controllers
Terminals
Device controllers
Disks & tape
Memory controller
Physical memory
*NIX Kernel
User level
File System
IPC
Process
Control
System
Device
Driver
Scheduler
Memory
Management
Hardware Control
Hardware
Kernel Space
kswapd (5)
root (0)
User Space
init (1)
sh
sh
sh
Qun l cc qu trnh
a nhim
Tc v -> process.
Mi process c:
Khng gian a ch (address space)
Code thc thi
Cc vng cha d liu
Stack
Danh nh ca process
Process identifier (PID) duy nht, tng dn t 0
Mt s PID c bit:
0: root
1: init
B nh ca process
Text: cha chng trnh code thc thi - cha cc
cc instruction dnh cho CPU thc hin - read only.
Data: vng d liu - cha cc bin c khai bo
tnh hoc ng - xin cp pht trong lc thc thi.
Stack: cha trng thi v cc thng tin lin quan n
vic gi hm.
Cu trc b nh
Process memory layout:
Text segment (code)
Data segment
High address
argc/argv[]
Stack segment
Stack
Heap
Command-line
arguments
Environment variables
Heap
end
edata
Uninitialized data
Initialized data
etext
Low address
Text segment
Cu trc b nh
a ch b nh
a ch do process tham kho ch l a ch o
C th truy xut thng tin b nh qua cc bin
ton cc:
etext: a ch sau vng text
edata: a ch kt thc vng initialized data
end: a ch bt u vng heap
nh ngha macro in a ch mt bin
#define PADDR(x) printf(#x " at %u\n", &x);
V d
#include <stdio.h>
#include <stdlib.h>
#define PADDR(x) printf(#x " at %u\n", &x);
extern unsigned etext, edata, end;
int a = 0, b;
int main(int argc, char *argv[]) {
printf("End of text seqment at %u\n", &etext);
printf("End of initialized statics and externals at %u\n", &edata);
printf("End of uninitialized statics and externals at %u\n", &end);
PADDR(a);
PADDR(b);
return 0;
}
Khoa Cng ngh
ngh Thng tin -
i h
hc B
Bch Khoa Tp. HCM
2.47
Ly i s v bin mi trng
Chng trnh C
int main(int argc, char *argv[]) {
}
Trong
int argc: s tham s ca chng trnh khi chy
char *argv[]: danh sch cc tham s
$ ./myapp 12 34 56 78
argc
argv
55
"./myapp"
"34"
"78"
"12"
"56"
V d
#include <stdio.h>
#include <stdlib.h>
extern char **environ;
int main(int argc, char *argv[]) {
int i;
printf("\nNumber of arguments is %d",argc);
printf("\nArguments:\n");
for(i=0; i<argc; i++)
printf("argv[%d]=%s\n",i,argv[i]);
getchar();
for (i=0; environ[i]!=(char *)0; i++)
printf("%s\n",environ[i]);
return 0;
}
Khoa Cng ngh
ngh Thng tin -
i h
hc B
Bch Khoa Tp. HCM
2.50
Ly PID ca process
#including
<unistd.h>
pid_t getpid(void);
V d
#include <stdio.h>
#include <unistd.h>
int main() {
printf("Process id: %d\n", getpid());
printf("Parent process id: %d\n", getppid());
return 0;
}
To process
H iu hnh to process bng cch nhn bn mt
process ang tn ti.
Process mi c to ra gi l con (child), process kia
l process cha (parent).
Parent
fork()
Child
wait()
Parent
Process
Parent
Process
fork()
Zombie
Process
Child
Process
Child
Process
exec
exit
To process
Dng hm: pid_t fork(void);
Nu thnh cng:
tr v 0 trong thn process con
PID ca con (>0) trong thn process cha.
V d
Dng mu chng trnh
pid_t pid;
pid = fork();
if (pid==0) {
// child code here
} else if (pid > 0) {
// parent code here
} else {
// error warning
}
To process
Parent process
Text
Data
fork()
Stack
Child process
Text
Data
Stack
V d
#include <stdio.h>
#include <unistd.h>
int main() {
int childid;
if ((childid=fork())==0) {
printf("Child process output: PID = %d\n",getpid());
printf("My parent PID is %d\n",getppid());
}else if(childid > 0) {
printf("Parent process output: PID= %d\t", getpid());
printf("Child PID=%d\n", childid);
}else {
printf("Fork error !\n");
exit(1);
}
return 0;
}
Khoa Cng ngh
ngh Thng tin -
i h
hc B
Bch Khoa Tp. HCM
2.58
Kt thc process
Dng system call exit():
Orphaned process: process cha kt thc trc
process con sau s c cha l init (PID=1)
Zombied process
Process kt thc nhng cha bo trng thi cho
process cha bit.
Dng hm wait() hay waitpid() process cha
ly trng thi tr v t process con.
Kt thc process
waitpid() system call:
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *stat_loc, int options);
(Tr v PID ca process con kt thc, hoc -1 nu tht bi)
i s pid :
<-1: i cc process con c process group ID bng vi PID ca n
= -1: i bt k cc process con no
= 0: i bt k cc process con no c process group ID bng vi
PID ca n.
> 0: i pocess c PID bng vi gi tr ny
Kt thc process
wait() system call:
#include <sys/types.h>
#include <sys/wait.h>
V d
#include <stdio.h>
#include <unistd.h>
#define PROCESSES 3
/*Number of processes */
V d (tip theo)
/* Execution of child processes */
if( retval == 0 ) {
child_no = count;
printf("Child #%d has PID (process-id):#%d\n",
getpid());
sleep(rand()%5);
}
else {
/* Waiting for children termination */
for( count = 0; count < PROCESSES; count++ )
wait(NULL);
}
return 0;
}
Khoa Cng ngh
ngh Thng tin -
i h
hc B
Bch Khoa Tp. HCM
2.63
V d:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv) {
if(!system("ls -l /"))
printf("Call system() OK!\n");
return 0;
}
Khoa Cng ngh
ngh Thng tin -
i h
hc B
Bch Khoa Tp. HCM
2.65
Cc hm exec()
Cc hm exec() thc hin nh sau:
Cc hm exec()
Ch
Cc hm exec s thay th process gi hm bng chng trnh
tng ng trong tham s nhp ca hm. Vng text, data, stack b
thay th, vng u (user area) khng b thay th.
Chng trnh c gi bt u thc thi hm main() (entry point),
c th nhn tham s nhp thng qua cc tham s truyn vo cc
hm exec.
$ ls -R /usr /lib
...
execl(
Cc hm exec()
Phn tch tn gi cc hm exec()
int execl (const char *path, const char *arg, ...)
int execv (const char *path, const char *argv[ ])
Hm c cha k t v (execv, execvp, execve) accept the argument
list for the new program as a NULL-terminated array of pointers to
strings. Functions that contain the letter l (execl, execlp, and execle)
accept the argument list using the C languages varargs mechanism.
Cc hm exec()
Phn tch tn gi cc hm exec()
Hm c cha k t v (execv, execvp, execve) accept the argument
list for the new program as a NULL-terminated array of pointers to
strings. Functions that contain the letter l (execl, execlp, and execle)
accept the argument list using the C languages varargs mechanism.
Functions that contain the letter p in their names (execvp and
execlp) accept a program name and search for a program by that
name in the current execution path; functions that dont contain the
p must be given the full path of the program to be executed.
Functions that contain the letter e in their names (execve and
execle) accept an additional argument, an array of environment
variables.The argument should be a NULL-terminated array of
pointers to character strings. Each character string should be of the
form VARIABLE=value
Cc hm exec()
Phn tch tn gi cc hm exec()
Hm c cha k t v (execv, execvp, execve) accept the argument
list for the new program as a NULL-terminated array of pointers to
strings. Functions that contain the letter l (execl, execlp, and execle)
accept the argument list using the C languages varargs mechanism.
Functions that contain the letter p in their names (execvp and
execlp) accept a program name and search for a program by that
name in the current execution path; functions that dont contain the
p must be given the full path of the program to be executed.
Functions that contain the letter e in their names (execve and
execle) accept an additional argument, an array of environment
variables.The argument should be a NULL-terminated array of
pointers to character strings. Each character string should be of the
form VARIABLE=value
Tm tt v cc hm exec()
Argument
Format
Search of
PATH
Automatic?
execl(...)
list
yes
no
execv(...)
array
yes
no
execle(...)
list
no
no
execve(...)
array
no
no
execlp(...)
list
yes
yes
execvp(...)
array
yes
yes
Library Call
Name
V d
V d execlp()
#include <stdio.h>
#include <unistd.h>
void main() {
execlp("/sbin/ifconfig","/sbin/ifconfig","-a",0);
}
Dch v chy:
$gcc ex1.c o ex1
$./ex1
eth0 Link encap:Ethernet HWaddr 00:60:8C:84:E6:0E
......
V d
V d execv()
#include <stdio.h>
#include <unistd.h>
void main(int argc, char *argv[]) {
execv("/sbin/ifconfig",argv);
}
Dch v chy:
$gcc ex2.c o ex2
$./ex2 -a
eth0
V d
#include <stdio.h>
child_argv[2] = argv[1];
#include <stdlib.h>
child_argv[3] = 0;
#include <errno.h>
exit(127);
}
do {
if (waitpid(pid, &status, 0) == -1) {
if (argc == 1)
if (errno != EINTR)
return 1;
return -1;
pid = fork();
} else
if (pid == -1)
return status;
return -1;
} while(1);
if (pid == 0) {
return 0;
child_argv[0] = "sh";
child_argv[1] = "-c";