使用多进程 + 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;
}
一个伪装的终端