1.c

来自「UNIX下编程实现带参数的简单shell.包含1.c、apue.h、error2」· C语言 代码 · 共 52 行

C
52
字号
#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 + =
减小字号Ctrl + -
显示快捷键?