我正在编写一个简单的程序来更好地理解fork(),wait()和execvp()。我的问题是,在我运行程序后,控件没有传回shell,我不知道为什么。我想要的是能够在代码完成后将另一个命令输入shell。我看了this,但我不认为这适用于我的情况。我基本上只是从here找到的复制代码。
输入/输出(#在我输入的行的前面,但不是输入的一部分):
shell> # gcc test.c -o test
shell> # ./test
input program (ls)
# ls
input arg (.)
# .
test test.c extra.txt
# a;dlghasdf
# go back
# :(
我的代码:
int main(void) {
//just taking and cleaning input
printf("input program (ls)\n");
char inputprogram [5] = {0,0,0,0,0};
fgets(inputprogram,5,stdin); //read in user command
int i;
for(i = 0; i < 5; i++) {
if(inputprogram [i] == '\n' ){
inputprogram[i] = 0;
}
}
printf("input arg (.)\n");
char inputarg [5] = {0,0,0,0,0};
fgets(inputarg,5,stdin); //read in user command
for(i = 0; i < 5; i++) {
if(inputarg [i] == '\n' ){
inputarg[i] = 0;
}
}
char per []= {inputarg[0], 0};
char *arg [] = {inputprogram, per , NULL};
int status = 0;
pid_t child;
//the fork(), execvp(), wait()
//////////////////////////////////
if ((child = fork()) < 0) {
/* fork a child process */
printf("*** ERROR: forking child process failed\n");
exit(1);
} else if(child == 0){
execvp(inputprogram, arg);
exit(1);
} else {
while(wait(&status != child));
}
return EXIT_SUCCESS;
}