【发布时间】:2018-03-23 07:50:35
【问题描述】:
我必须制作简单的外壳来读取命令并按顺序执行它们。条件不会改变主函数的形式,执行函数应该是递归的。 主要问题是它似乎 waitpid 不起作用。但我知道,我的代码中有很多问题。请让我知道我应该从哪里开始..
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX 10
char cmmd[MAX][256];
int sp;
char *argv[10];
int size;
void ClearLineFromReadBuffer(void){
while(getchar() != '\n');
}
void printCommands(){
size = sp+1;
//print by moving stack pointer
while(1){
if (sp==-1) break;
printf("Command line : %s\n", cmmd[sp]);
sp--;
}
printf("print end\n");
}
void readCommandLines(){
int a = 0; //return of scanf
while (1){ //write commends to cmmd untill get ctrl+d
printf(">");
a = (scanf("%[^\n]s", cmmd[sp])); //take input to str untill get enter(scanf returns -1)
if (a==-1) {sp--; break;}
if (a==1) ClearLineFromReadBuffer();
if (a==0) {printf("error"); break;}
sp++;
}
printf("\n");
}
void readACommand(char *line){ //line takes string's name.
int i=0;
argv[i]=strtok(line," "); //i==0
while(strtok(line," ")!=NULL){
i++;
argv[i]=strtok(NULL," ");
}
printf("%s",argv[0]);
printf("%s",argv[1]);
}
void executeCommands(){ //Recursive function
int n = sp;
n++;
printf("%d",n);
printf("%s",cmmd[n]);
char *cmd_line = cmmd[n]; //command line which child process will execute
unsigned int child_pid; //fork() returns process id of child in parents process
int status; //status takes return of child's exit()
child_pid=fork();
if (child_pid != 0){ // Parents process
printf("parents access");
waitpid(child_pid,&status,0);
printf("***Process %d Child process %d DONE with status %x\n\n",getpid(),child_pid,status);
sp++;
if(sp<size)
executeCommands();
}
else if (child_pid == 0){ //fork() returns 0 in child process
printf("***Process %d Executing Command %s",getpid(),cmd_line);
readACommand(cmmd[n]);
execve(argv[0],argv,NULL);
printf("ERROR - not executing command \"%s\"\n",argv[0]); //can be printed because exec() failed
}
}
int main(){
readCommandLines();
printCommands();
executeCommands();
return(0);
}
【问题讨论】:
-
可能相关:您必须
NULL终止您的参数列表。 -
您的标记化循环非常可疑。我认为如果超过 2 个参数,它可能是无限的。而且它不会以 NULL 终止。
-
谢谢你。我修复并成功将其分开,但循环永远不会结束。你能告诉我什么是物质吗?当我尝试打印每个 argv 时,它可以打印到最后一个参数,但仍停留在 while 循环中。
-
非常感谢您的回答!这很有帮助,我理解我的错。谢谢
-
如果有帮助,您可以接受答案。 stackoverflow.com/help/someone-answers
标签: c linux shell operating-system system-calls