编写代码实现伪终端

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/wait.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <arpa/inet.h>

char* getLine(char* buf,int size){
    fgets(buf,size,stdin);//将标准输入流写入buf
    int len = strlen(buf);
	//在可变参的最后加入0,表示可变参的结束位
    if(buf[len-1]=='\n'){
        buf[len-1] = 0;
    }
}

int main(int argc, const char *argv[])
{
    while(1){
		//父进程循环fork出新的子进程,子进程被替换就变成僵尸进程了
        int retval = fork();
		if(retval > 0){
            wait(0);//阻塞父进程,吸收僵尸子进程
        }else{
            char* username = getlogin();//返回与当前用户关联的登录名
            char hostname[64] = {0};//创建一个字符数组,用于接收网络名
            char pwd[128] = {0};//创建一个字符数组,用于接收绝对路径

			//把网络名写入hostname字符串
			gethostname(hostname,64);
			//将当前工作目录的绝对路径复制到参数pwd所指的内存空间中
            getcwd(pwd,128);
			//显示伪终端
            printf("\033[1;32;10m%s@%s\033[0m:\033[1;34;10m%s\033[0m$ ",username,hostname,pwd);
            fflush(stdout);//刷新缓存区

            char* arg[20] = {0};//初始化一个字符指针数组
            // find /usr/include -name stdio.h
            // cd ..
            char cmd[128] = {0};//接收标准输入流的数据
            getLine(cmd,128);//函数调用,写入标准输入流

            char* retval = NULL;//初始化一个字符指针
            int i = 0;
            do{
                if(retval == NULL){
                    retval = strtok(cmd," ");//以空格分割标准输入流的字符串
                }else{
                    retval = strtok(NULL," ");//继续往后分割
                }
            //    printf("retval = %s\n",retval);
                arg[i++] = retval;//将数据地址写入arg指针数组
            }while(retval != NULL);

			//模拟cd功能,子进程替换成shell指令
            if(strcmp(arg[0],"cd")==0){//判断写入的字符是否是cd
                chdir(arg[1]);//如果是cd,就模拟切换目录到cd
            }else{
                execvp(arg[0],arg);//模拟终端的其他指令,替换到当前进程运行
            
                printf("没有找到该指令\n");//指令错误
            }
		}
    }
    return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值