Linux的父进程、子进程执行顺序

本文详细解析了Linux环境下使用fork函数创建子进程的过程,并通过代码实例展示了其应用,包括修改后的程序实现的功能及执行结果分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  昨天看了Linux的进程管理,写一写学到的一点知识。

  父进程用调用fork()函数可以创建子进程,并把所有信息复制给子进程。

  先看一段C代码:

  

#include<stdio.h>
#include<unistd.h>
int main()
{
    int pid;
    printf("first process\n");
    printf("calling fork\n");
    pid = fork();
    if(0 == pid)
        printf("I am the child\n");
    else if(0 < pid)
        printf("I am the father\n");
    else
        printf("error\n");
    printf("program end\n");
    return 0;
}

  执行结果:

  first process

  calling fork

  I am the father
  program end
  I am the child
  program end

  

  修改后的程序:

  

View Code
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
    int pid;
    printf("one process\n");
    printf("calling fork\n");
    pid = fork();
    if(0 == pid){
        printf("I am the child\n");
        execl("/bin/ls","ls","-l","forktest.c",NULL);
        perror("exec error");
        exit(1);
    }
    else if(0 < pid){
        wait(NULL);
        printf("I am the parent\n");
    }
    else
        printf("fork error\n");
    printf("program end\n");
    return 0;
}

  执行的结果为:  

  one process
  calling fork
  I am the child
  -rw-rw-r-- 1 chendi chendi 289 Jan 12 13:19 forktest.c
  I am the parent
  program end

  

转载于:https://www.cnblogs.com/chendi2012/archive/2013/01/13/2858423.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值