2016-09-12 6 views
1

私は以下のようにCシェルの初めを実装しました。これまで私はリダイレクトを働かせていました。同様の方法で、しかし難しさを持っています。 誰も助けることができますか? パイプ演算子を調べてから、sa [i-1]とsa [i + 1]を別々の2つのコマンドとして保存しますが、fork()とexecこの。私自身のCシェルでの配管

int startProcess (StringArray sa) 
{ 
    int pid; 
    int status; 
    int fd1; 
    int fd2; 
    int current_in; 
    int current_out; 
    int fd0; 
    int fd00; 
    int in = 0; 
    int out = 0; 
    char input[64]=""; 
    char output[64]=""; 
    char cmd1[64] =""; 
    char cmd2[64] =""; 
    int fd[2]; 
    int pipe = 0; 

    switch(pid = fork()){ 
case -1://This is an error 
    perror("Failure of child."); 
    return 1; 
case 0: // This is the child 
    // Redirection 


    /* finds where '<' or '>' occurs and make that sa[i] = NULL , 
     to ensure that command wont' read that*/ 

    for(int i=0;sa[i]!='\0';i++) 
    { 
     if(strcmp(sa[i],"<")==0) 
     {   
      sa[i]=NULL; 
      strcpy(input,sa[i+1]); 
      in=2;   
     }    

     if(strcmp(sa[i],">")==0) 
     {  
      sa[i]=NULL; 
      strcpy(output,sa[i+1]); 
      out=2; 
     } 

    } 

    //if '<' char was found in string inputted by user 
    if(in) 
    { 

     // fdo is file-descriptor 
     int fd0; 
     if ((fd0 = open(input, O_RDONLY, 0)) < 0) { 
      perror("Couldn't open input file"); 
      exit(0); 
     }   
     // dup2() copies content of fdo in input of preceeding file 
     dup2(fd0, 0); // STDIN_FILENO here can be replaced by 0 

     close(fd0); // necessary 
    } 

    //if '>' char was found in string inputted by user 
    if (out) 
    { 

     int fd00 ; 
     if ((fd00 = creat(output , 0644)) < 0) { 
      perror("Couldn't open the output file"); 
      exit(0); 
     }   

     dup2(fd00, STDOUT_FILENO); // 1 here can be replaced by STDOUT_FILENO 
     close(fd00); 
    } 


      execvp(sa[0], sa); 
      perror("execvp"); 
      _exit(1); 


    printf("Could not execute '%s'\n", sa[0]); 
    default:// This is the parent 
    wait(&status); 
    return (status == 0) ? 0: 1; 
    } 
} 
+2

SOや他のサイトでこの正確な問題を扱う多くの質問があります。何か検索しましたか?あなたが本当に助けを望むなら、「私はfork()とexec()を正しく行う方法がわかりません」より具体的な質問をする必要があります。その答えは 'fork'と' exec'を呼び出すことです。具体的にどのように行うのか分かりませんか? – kaylum

+0

はい、私は多くの検索をしました。私はいつ、どこで、どのようにSTDOUTとSTDINが配管で動作するのか理解できませんでした。 – rsa

答えて

1
  1. パイプを作成します。
  2. fork()
  3. 親では、STDOUTファイル記述子(1)をパイプの入力に設定します。
  4. 子プロセスで、STDINファイル記述子(0)をパイプの出力に設定します。親と子の両方で
  5. exec()です。

fork()のように、リダイレクトの場合と同じように、この後のすべてのことを子供の中で行います。

関連する問題