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

  昨天看了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

  

posted @ 2013-01-13 15:15  长溪  阅读(2522)  评论(1编辑  收藏  举报