20165220 mybash

使用fork,exec,wait实现mybash
- 写出伪代码,产品代码和测试代码
- 发表知识理解,实现过程和问题解决的博客(包含代码托管链接)

1、fork

功能:创建一个新的进程

一个现存进程调用fork函数是linux内核创建一个新进程的唯一方法(交换进程、init进程和页精灵进程并不是这样,这些进程是由内核作为自举过程的一部分以特殊方式创建的)。

参数:pid_t fork(void);
返回值:一个是子进程返回0,第二个是父进程的返回值大于0.错误返回-1.
头文件:include<unistd.h>

2、exec

功能:在用fork函数创建子进程后,子进程往往要调用一个exec函数以执行另一个程序

当进程调用一种exec函数时,该进程完全由新程序代换,而新程序则从其main函数开始执行。因为调用exec并不创建新进程,所以前后的进程I D并未改变。exec只是用另一个新程序替换了当前进程的正文、数据、堆和栈段。

返回值:成功了没返回值,失败了返回-1.
头文件:

#include<unistd.h>

3、wait

功能:等待进程
参数:pid_t wait(int*status);返回值:调用成功,返回子进程的PID,发生错误返回-1。错误原因放在全局变量errno中
头文件:
#include<sys/types.h>

#include<sys/wait.h>

waitpid
函数说明:在一个子进程结束之前,wait使其调用者阻塞,waitpid使用WNOHANG参数以非阻塞方式等待子进程,waitpid可以指定所需要等待的子进程。

二、实现bash

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>

void main()
{
        
    char *command[3];
    command[0] = "ls";
    command[1] = "-l";
    command[2] = 0;
        
        int s,i=0;
        int rtn; 
        printf( ">" );
    //printf("%s %s %s",command[1],command[2],command[3]);  
    printf("%s",command[0]);
    i=0;    
    s=fork();
    if ( s== 0 ) {
    //printf("%d
",s);
    execvp( command[0], command );
    
    //perror( command );
    
    exit( errno );
     }
     else {
    
    //printf("%d
",s);

    wait ( &rtn );
    
    printf( " child process return %d
", rtn );
    
    }
    }

实验结果

 

原文地址:https://www.cnblogs.com/brs6666/p/10018186.html