1. ps命令的介紹
leichaojian@ThinkPad-T430i:~$ ps -la
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 R 1000 4133 4048 0 80 0 - 3545 - pts/0 00:00:00 ps
S: 代表進程的狀態:爲S則代表睡眠,爲R則代表運行。
UID,PID,PPID:用戶ID,進程ID,父ID
PRI:進程的優先級
NI:進程的niceness級別
SZ:進程的大小
WCHAN:睡眠的原因
2. 子進程的例子
1) 子進程和父進程的返回值
#include <stdio.h>
int main( void )
{
int ret_from_fork, mypid;
mypid = getpid();
printf("before: my pid is %d\n", mypid );
ret_from_fork = fork();
sleep( 1 );
printf("after:my pid is %d, fork() said %d\n", getpid(), ret_from_fork);
}
程序輸出:
leichaojian@ThinkPad-T430i:~$ ./a.out
before: my pid is 12554
after:my pid is 12554, fork() said 12555
after:my pid is 12555, fork() said 0
函數種sleep的作用是:讓子進程先完成並退出,然後繼續父進程的執行。而fork函數向父進程返回子進程的ID,向子進程返回0。
2) 子進程調用子進程
#include <stdio.h>
int main( void )
{
printf("my pid is %d\n", getpid());
fork();
fork();
fork();
printf("my pid is %d\n", getpid());
return 0;
}
~
程序輸出:
leichaojian@ThinkPad-T430i:~$ ./a.out
my pid is 2983
my pid is 2983
my pid is 2985
my pid is 2988
my pid is 2984
my pid is 2986
my pid is 2989
my pid is 2987
my pid is 2990
3. 初識腳本
1)腳本小程序
#this is called script0
#it runs some commands
ls
echo the current date/time is
date
echo my name is
whoami
程序輸出:
leichaojian@ThinkPad-T430i:~$ sh script0
ac.c Downloads logout_tty.c rotate.c Templates
a.out echostate.c ls.c script0 test.c
cli.c examples.desktop more01.c serv.c tt.c
coreutils-8.23 foo more.c setjmp.c Videos
coreutils-8.23.tar.xz fork1.c Music sig.c who1.c
cp.c fork2.c Pictures sig.c~ whoami.c
cp_new.c hello1.c play_again.c sleep1.c whoami.c~
cptemp linux-3.16.1 psh1.c sleep2.c who.c
Desktop listchars.c Public sleep3.c whosrc.c
Documents logout_tty pwd.c sleep4.c
the current date/time is
2014年 09月 01日 星期一 22:34:39 CST
my name is
leichaojian
其中,echo用來顯示字符。
#!/bin/sh
#script2:a real program with variables, input and control flow
BOOK=$HOME/phonebook.data
echo find what name in phonebook
read NAME
if grep $NAME $BOOK > /tmp/pb.tmp
then
echo Entries for $NAME
cat /tmp/pb.tmp
else
echo No entries for $NAME
fi
rm /tmp/pb.tmp
程序輸出:
leichaojian@ThinkPad-T430i:~$ chmod +x script2
leichaojian@ThinkPad-T430i:~$ ./script2
find what name in phonebook
dave
Entries for dave
dave 432-6546
leichaojian@ThinkPad-T430i:~$ ./script2
find what name in phonebook
fran
No entries for fran
leichaojian@ThinkPad-T430i:~$ cat $HOME/phonebook.data
ann 222-3456
bob 323-2222
carla 123-4567
dave 432-6546
eloise 567-9876
這裏fi代表if的結束。