进程基础知识
1、通过ubuntu上的系统监视器界面,查看进程状态:
2、fork and exec systme function
(1) ProcessExec.c :
#include <stdio.h>
#include <unistd.h>
int main(){
printf("=====system call execl testing==========\n");
//execl("/bin/date", "/bin/date", 0);
execlp("date", "date", 0);
printf("exec error!\n");
return 0;
}
(2) ProcessExce2.c: 对某一指定文件进行监视,当所监视的文件修改后,自动为它建立一个副本。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char * argv[]){
int fd;
int stat, pid;
struct stat stbuf;
time_t old_time;
if(argc != 3){
fprintf(stderr, "Usage: %s watch file copyfile \n", argv[0]);
return 1;
}
if((fd = open(argv[1], O_RDONLY)) == -1){
fprintf(stderr, "Watchfile: %s can't open\n", argv[1]);
return 2;
}
fstat(fd, &stbuf);
old_time = stbuf.st_mtim.tv_sec;
for(;;){
fstat(fd, &stbuf);
if(old_time != stbuf.st_mtim.tv_sec){
pid = fork();
if(pid==0){
printf("child process start copy file!");
execl("/bin/cp", "/bin/cp", argv[1], argv[2], 0);
return 3;
}
wait(&stat);
old_time = stbuf.st_mtim.tv_sec;
}
else{
sleep(30);
}
}
}
注:可以在shell控制台执行: $./helloworld file file.bak
(主线程监视file文件,如果file文件改变,主线程30秒内检测到,会创建一个file.bak的备份文件)
(3) ProcessExec3.c:
/*
* ProcessExec3.c
*
* Created on: Jul 24, 2013
* Author: root
*/
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
void statport(int,int);
int main(int argc, char * argv[]){
int i, pid, stat;
char *p;
if(argc <= 1){
printf("Usage %s cmd1 cmd2 ...\n", argv[0]);
exit(1);
}
for(i=1, p=argv[i]; argc > 1; p=argv[i]){
printf("====[%d]:command '%s' begin=====\n", i, p);
if((pid=fork()) == 0){
printf("Child pid=%d\n", getpid());
execl(argv[i], argv[i], 0);
exit(argc);
}
pid=wait(&stat);
statport(pid, stat);
argc--;
printf("====[%d]:command'%s' end=====\n\n", i++, p);
}
}
struct sigway{
char * sigstr;
int value;
};
struct sigway sigways[] = {
"hup",1, "int",2,"quit",3,"ill",4,"trap",5,"iot",6,"abrt",7,"emt",8,
"fpe",9, "kill",10,"bus",11,"segv",12,"sys",13,"pipe",14,"alrm",15,
"gterm",16,"user1",17,"user2",18,"cld",19,"pwr",20,"poll",21,(char*)0,0
};
void statport(int pid, int stat){
int i;
if(pid==-1){
printf("bad wait\n");
}
else if((stat & 0177) == 0177){
i=stat >> 8;
printf("child process: %d stop by signal\n", pid);
printf("Signal name:%s\n", sigways[i].sigstr);
printf("Singal value:%d\n", sigways[i].value);
}
else if((stat & 0xff) == 0){
printf("Child process: %d exit by 'exit' system call.\n", pid);
printf("exit code: %d\n", stat >> 8);
}
else if((stat >> 8) == 0){
if((stat & 0200) == 0200){
printf("child process:%d'-core dumped' by signal\n", pid);
}
}
}
注:该函数功能为执行从命令行中一次提交的多条不带参数的命令,并且分析进程终止的原因。