1 Unix Processes
1.OS决定哪个进程在何时使用CPU
2 The Death of a Process
1.在main
中终断自己
2.1 exit() and _exit() and _Exit()
-
三种终断进程的方法
方法|描述
–|--
_exit()|请求OS立刻终断进程,强行,不回收资源
exit()|C标准库函数,先回收资源,再终断
_Exit()|C标准库函数,本质是_exit()
的包装 -
图片解释
_exit
绿色直接退出exit
红色,回收I/O,等后才调用_exit
2.2 I/O Buffering and Exit Procedures
1.左图exit
会先将buffer里的内容输出的屏幕,再退出
2.右图_exit
不会等待,直接退出
3.可以调用fflush()
将buffer内容输出
2.3 Changing I/O Buffering policy
1.stdout and stdin is line buffered(标准输入和输出缓冲区遇到换行才会输出)
2.stderr is unbuffered(标准错误因为立刻输出,所以消耗资源会很大)
3.fully buffered,which means writes/reads occur once the buffer is full.(当超过设定的buffer长度才会输出)
4.通过setvbuf
来设置buffer
效果
/*_exit_IO_setvbuf.c*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
//stderr is now Line buffered
setvbuf(stderr, NULL, _IOLBF, 0);
// I/O now buffered for stderr
fprintf(stderr, "Will NOT print b/c stderr is now line buffered");
_exit(0); //immediate exit!
}
2.4 atexit() Exit Handlers
1.终断exit()
时回调其他函数
/*exit_handler_demo.c*/
#include <stdio.h>
#include <stdlib.h>
void my_exit1(){
printf("FIRST Exit Handler\n");
}
void my_exit2(){
printf("SECOND Exit Handler\n");
}
int main(){
//exit handers execute in reverse order of registration
atexit(my_exit1);
atexit(my_exit2);
//my_exit2 will run before my_exit1
return; //implicitly calls exit()
}
2.5 Exit Statuses
1.0:sucess;1:failure;2:error
_exit(int status);
exit(int status);
_Exit(int status);
3 The Birth of a Process
1.程序开始于main()
,在main
前会调用其他函数来配置进程所需要的环境
3.1 Exec System Calls
/* exec_ls.c*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char * argv[]){
//arguments for ls
char * ls_args[2] = { "/bin/ls", NULL} ;
//execute ls
execv( ls_args[0], ls_args);
//only get here if exec failed
perror("execve failed");
return 2; //return error status
}