IO/作业/2024/7/18

使用多进程 + wait + exec + strtok 实现

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
 
typedef struct sockaddr_in addr_in_t; 
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
 
char* getLine(char* buf,int size)
{
    fgets(buf,size,stdin);
    int len = strlen(buf);
    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 if(retval == 0)
		{
            char* username = getlogin();
            char hostname[64] = {0};
            char pwd[128] = {0};
            gethostname(hostname,64);
            getcwd(pwd,128);
            printf("\033[1;32;10m%s@%s\033[0m:\033[1;34;10m%s\033[0m$ ",username,hostname,pwd);
            fflush(stdout);
			// 输入shell指令
            char* arg[20] = {0};
            char cmd[128] = {0};
            getLine(cmd,128);
 
            char* retval = NULL;
            int i = 0;
           	// do while 循环在执行什么操作:将shell里面的每一个以 空格
			// 为分隔符的字符串分割出来后,放到 arg 字符串数组里面去
			do
			{
                if(retval == NULL)
				{
                    retval = strtok(cmd," ");
                }
				else
				{
                    retval = strtok(NULL," ");
                }
                arg[i++] = retval;
            }while(retval != NULL);
 
            if(strcmp(arg[0],"cd")==0)
			{
                chdir(arg[1]);
            }
			else
			{
                execvp(arg[0],arg);
            
                printf("没有找到该指令\n");
            }
        }
    }
	return 0;
}

一个伪装的终端

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值