系统级程序设计总结笔记(二)
侧边栏壁纸
  • 累计撰写 40 篇文章
  • 累计收到 134 条评论

系统级程序设计总结笔记(二)

yjprolus
2022-05-06 / 2 评论 / 15 阅读 / 正在检测是否收录...

几个重要知识点

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

几个问题

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

代码

案例2

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
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

运行结果

案例3

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

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
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()仅仅被调用一次,却能够返回两次
0

评论 (2)

取消
  1. 头像
    网上邻居
    Windows 8 · Google Chrome

    康一康

    回复
  2. 头像
    元气少女郭德纲
    MacOS · Google Chrome

    支持支持

    回复