进程管理x

本文介绍了进程管理的基础知识,包括使用fork()创建子进程,exec()执行新程序,以及孤儿进程的概念。通过示例代码展示了fork()的使用,解释了为何在某些情况下子进程的父进程ID会变为1。此外,还讨论了进程同步的重要性,通过案例分析展示了如何通过控制进程执行顺序避免数据竞争问题。
摘要由CSDN通过智能技术生成
  • 掌握进程属性与处理机制
  • 用fork(),exec()等系统调用创建进程
  • 进程同步
  • 常用进程管理命令

fork

  • 执行后,会创建一个子进程
  • 继承父进程的部分数据

案例1:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
    pid_t tempPid;
    tempPid = fork();
    if(tempPid == -1){
        perror("fork error");
    }else if(tempPid > 0){//parent
        printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
    }else{//child
        printf("child process, pid = %d, ppid = %d\n", getpid(), getppid());
    }//of if
    printf("......finish......");
    return 0;
}//of main

在这里插入图片描述
多次执行后,child process 输出的ppid 不等于 父进程的id了
变成了1

因为父进程优先于子进程结束,子进程变成"孤儿进程",由init进程来接收(init进程的pid为1)

案例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......");
    return 0;
}//of main
————————————————

在这里插入图片描述

案例3:

#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......");
    return 0;
}//of main

等待了一定时间后才进行输出 sleep() 函数
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值