系统级程序设计(二 )

文章目录

  • 几个重要知识点
  • 几个问题
  • 代码
    • 案例2
    • 案例3
  • 总结心得

几个重要知识点

  • 孤儿进程
  • 父进程和子进程
  • init进程的作用
  • sleep函数

几个问题

  • 多次执行test_fork会发现,child process后输出的ppid不等于parent process的pid,而等于1:父进程先于子进程终止,子进程变成“孤儿进程”,后面由init进程来接收
  • 子进程的编号不是递增的:子进程应由父进程回收,但是当子进程被创建后,它与它的父进程及其它进程共同竞争系统资源,所以父子进程执行的顺序是不确定的,终止的先后顺序也是不确定的。简单来说,所有进程优先级是相同的,不会按进程号运行
  • *终端提示符后面仍然有子进程信息打印,而命令提示符在最后一行的开头闪烁:*进程还没完全运行完

代码

案例2

#include 
#include 
#include 
int main(){
	pid_t tempPid;
	int i;
	for(i = 0; i < 2; i ++){
		if((tempPid = fork()) == 0){
			break;
		} //of if
	} //of for i
	if(tempPid == -1){
		perror("fork error");
	}else if(tempPid > 0){ //parent
		printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
	}else{ //child
		printf("I am child process = %d, pid = %d, ppid = %d\n", i + 1, getpid(), getppid());
	} //of if
	printf("---finish---by yjprolus");
	return 0;
} //of mains

运行结果
系统级程序设计(二 )_第1张图片

案例3

出现sleep函数的地方程序会延缓运行

#include 
#include 
#include 
int main(){
	pid_t tempPid;
	int i;
	for(i = 0; i < 2; i ++){
		if((tempPid = fork()) == 0){
			break;
		}//of if
	}//of for i
	if(tempPid == -1){
		perror("fork error");
	}else if(tempPid > 0){//parent
		sleep(2);
		printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
	}else{//child
	 	sleep(i);
		printf("I am child process = %d, pid = %d, ppid = %d\n", i + 1, getpid(), getppid());
	}//of if
	printf("---finish---by yjprolus");
	return 0;
}//of main

总结心得

学会了fork()的基本用法,对父进程和子进程有了更加清楚的认识,了解了Linux终端的进阶用法,对程序的运行优先级和进程管理有了更深的认识。

翻阅书籍和相关博客资料,补充如下:fork()函数遵循“读时共享,写时复制”的原则;fork()仅仅被调用一次,却能够返回两次

你可能感兴趣的:(系统级程序设计,linux,运维,c语言)