Cで簡単なシェルを実装したいのですが、リダイレクトが実現できません
lang
1#include<stdio.h> 2#include<stdlib.h> 3#include<unistd.h> 4#include<string.h> 5#include<fcntl.h> 6#include<sys/types.h> 7#include<sys/wait.h> 8 9#define MAX_LINE_IN 1000 10#define MAX_ARGS 30 11#define BUF_SIZE 256 12 13int nol(const char *s){ 14 int i; 15 FILE *f=fopen(s,"r"); 16 char buf[BUF_SIZE]; 17 18 if(!f){ 19 printf("ファイル読み込みエラー\n"); 20 exit(0);} 21 22 i=0; 23 24 while((fgets(buf,BUF_SIZE,f)) != NULL){ 25 i++; 26 } 27 if(fclose(f))exit(0); 28 29 return i; 30} 31void redirect(const char *args[],int a){//a:<のある位置 32 int fd,i; 33 34 args[a]=NULL; 35 fd=open(args[a+1],O_WRONLY | O_CREAT,0664);//rwrwrのこと 36 close(STDOUT_FILENO); 37 dup(fd); 38 execvp(args[0],args); 39 40} 41 42 int main(int argc, char *argv[]){ 43 int pid, status; 44 char line_in[MAX_LINE_IN]; 45 char *args[MAX_ARGS]; 46 int nargs; 47 int i; 48 49 ////tokenize 50 for(;;){ 51 printf("> "); 52 if(fgets(line_in,MAX_LINE_IN,stdin)==NULL)exit(0); 53 line_in[strlen(line_in)-1]='\0'; 54 55 char *token = strtok(line_in," "); 56 nargs=0; 57 args[nargs++]=token; 58 while(token!=NULL){ 59 token = strtok(NULL," "); 60 if(token!=NULL){ 61 args[nargs++]=token; 62 } 63 } 64 args[nargs] = NULL; 65 66 if(args[0]!=NULL){ 67 if(!strcmp(args[0],"exit")) 68 { 69 exit(1); 70 continue; 71 } 72 73 74 75 76 if(fork()==0){ 77 78 if(!strcmp(args[0],"nol")) 79 { 80 printf("%d\n",nol(args[1])); 81 exit(1); 82 } 83 for(i=0;i<nargs;i++) 84 { 85 if(!strcmp(args[i],">")) 86 { 87 redirect(args[0],i); 88 exit(1); 89 } 90 } 91 execvp(args[0],args); 92 printf("command not found\n"); 93 exit(1); 94 } 95 96 else{ 97 wait(&status); 98 } 99 100 } 101 102 } 103 return 0; 104 } 105
コンパイルすると以下の警告がでます
shell.c: In function ‘redirect’:
shell.c:38:18: warning: passing argument 2 of ‘execvp’ from incompatible pointer type [-Wincompatible-pointer-types]
execvp(args[0],args);
^
In file included from shell.c:3:0:
/usr/include/unistd.h:581:12: note: expected ‘char * const*’ but argument is of type ‘const char **’
extern int execvp (const char *__file, char *const __argv[
^
shell.c: In function ‘main’:
shell.c:87:13: warning: passing argument 1 of ‘redirect’ from incompatible pointer type [-Wincompatible-pointer-types]
redirect(args[0],i);
^
shell.c:31:6: note: expected ‘const char **’ but argument is of type ‘char *’
void redirect(const char *args[],int a){//a:<のある位�
実行後、echoコマンドで出力先を任意のファイルにリダイレクトしたいのですが新しいファイルが生成されません。
回答3件
あなたの回答
tips
プレビュー