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的结束。