⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 1.c

📁 UNIX下编程实现带参数的简单shell.包含1.c、apue.h、error2e.c
💻 C
字号:
#include "apue.h"
#include <sys/wait.h>

int main (void)
{
	char buf[MAXLINE];  /*from apue.h*/
	pid_t pid;
	int status;
	char *argv[MAXLINE];
	printf("%% ");   /* print promt (printf requires %% to print % */
	while(fgets(buf,MAXLINE,stdin) != NULL)
	{
		int i=-1,k=0,flag=0; /*flag to sign the first word*/
		if(buf[strlen(buf)-1]=='\n')
			buf[strlen(buf)-1 ]=0;  /*replace newline with null */
		if((pid =fork())<0)
		{
			err_sys("fork error");
		}else if(pid == 0)
		{/* child */
			while(buf[++i]!=0)
			{
				if(buf[i]!=' '&&flag==0) /*buf[i] now is the first word of the commmand*/
				{
					argv[k++]=&buf[i];
					flag=1;
				}
				else if(buf[i]==' '&& flag==0) /*too many soaces,it's wrong*/
				{
					argv[k++]=&buf[i];
				}
                                else if(buf[i]==' ' && flag==1)/*the space to seperate the word of the commmand*/
                                {
                                    buf[i]='\0';
                                    flag=0;
                                }
			}
			argv[k]=NULL;
                        execve(argv[0],argv, NULL);
			err_ret("couldn't execute: %s",buf);
			exit(127);
			
		}
		
		/* parent */
		if ((pid = waitpid(pid,&status, 0))<0)
			err_sys("waitpid error");
		printf("%% ");
	}
	exit(0);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -