入力で指定されたプログラムを実行する単純なシェルプログラムを作成しようとしています。主な機能には、scanner()
(トークンで入力を分割するのにstrtok
を使用)と(プロセスをフォークしてプログラムを実行する)の2つがあります。my_shellプログラムの文字列のバグ
残念ながらそれは動作しません...私はscanner()
の末尾にの最後にstring[0]
を印刷しようとしました。私は本当に理解することはできません
初めて出力が正しいですが、二度目string[]
がそうexecvp()
が動作しない乱数列に変更しているようだ...なぜstring[]
変化の値は、おそらく非常にばかげたエラーですが、私はそれを見ることができません。私は本当にあなたの助けが必要です!アドバイスをありがとう。
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#define DIM 256
int scanner(char*[]);
int execute(char*[]);
int main()
{
char* string[DIM];
scanner(string);
execute(string);
}
/* scan: read the input in token*/
int scanner(char* string[])
{
char input[1024];
char delimit[]=" \t\r\n\v\f";
int i = 0;
if(fgets(input, sizeof input, stdin)) {
string[i] = strtok(input, delimit);
while(string[i]!=NULL){
i++;
string[i]=strtok(NULL,delimit);
}
return 0;
}
return 1;
}
/* execute: execute the command*/
int execute(char* string[])
{
int pid;
printf("%s\n", string[0]);
switch(pid = fork()){
case -1:
return 1;
case 0:
execvp(string[0], string);
return 1;
default:
wait((int*)0);
return 0;
}
}
ありがとうございました!私はちょうど静的な入力を宣言しようとしましたが、今は動作します。 – sworwitz
あなたはそれが正しい解決策だと思いますか、他に何か試してみるべきですか? – sworwitz
静的宣言が機能しますが、配列の場合と同じように、mainからの入力として文字列変数を送ることもできます。 –