2015-04-08 26 views
0

我已經寫了一個程序(帶有來自SO的代碼),並且現在我應該實現錯誤處理。如何做到這一點?程序應該優雅地失敗,例如,當傳遞錯誤的參數時。我的程序應該如何處理錯誤?

#include <sys/types.h> 
#include <errno.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <string.h> 
struct command 
{ 
    const char **argv; 
}; 
/* Helper function that spawns processes */ 
int spawn_proc (int in, int out, struct command *cmd) { 
    pid_t pid; 
    if ((pid = fork()) == 0) { 
     if (in != 0) { 
      dup2 (in, 0); 
      close (in); 
     } 
     if (out != 1) { 
      dup2 (out, 1); 
      close (out); 
     } 
     return execvp (cmd->argv [0], (char * const *)cmd->argv); 
    } 
    return pid; 
} 
/* Helper function that forks pipes */ 
int fork_pipes (int n, struct command *cmd) { 
    int i; 
    int in, fd [2]; 
    for (i = 0; i < n - 1; ++i) { 
     pipe (fd); 
     spawn_proc (in, fd [1], cmd + i); 
     close (fd [1]); 
     in = fd [0]; 
    } 
    dup2 (in, 0); 
    return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv); 
} 

int main (int argc, char ** argv) { 
    int i; 
    if (argc == 1) { /* There were no arguments */ 
     const char *printenv[] = { "printenv", 0}; 
     const char *sort[] = { "sort", 0 }; 
     const char *less[] = { "less", 0 }; 
     struct command cmd [] = { {printenv}, {sort}, {less} }; 
     return fork_pipes (3, cmd); 
    } 
    if (argc > 1) { /* I'd like an argument */ 

     if (strncmp(argv[1], "cd", 2) && strncmp(argv[1], "exit", 2)) { 
      char *tmp; 
      int len = 1; 
      for(i=1; i<argc; i++) 
      { 
       len += strlen(argv[i]) + 2; 
      } 
      tmp = (char*) malloc(len); 
      tmp[0] = '\0'; 
      int pos = 0; 
      for(i=1; i<argc; i++) 
      { 
       pos += sprintf(tmp+pos, "%s%s", (i==1?"":"|"), argv[i]); 
      } 
      const char *printenv[] = { "printenv", 0}; 
      const char *grep[] = { "grep", "-E", tmp, NULL}; 
      const char *sort[] = { "sort", 0 }; 
      const char *less[] = { "less", 0 }; 
      struct command cmd [] = { {printenv}, {grep}, {sort}, {less} }; 
      return fork_pipes (4, cmd); 
      free(tmp); 
     } else if (! strncmp(argv[1], "cd", 2)) { /* change directory */ 
      printf("change directory to %s\n" , argv[2]); 
      chdir(argv[2]); 
     } else if (! strncmp(argv[1], "exit", 2)) { /* change directory */ 
      printf("exit\n"); 
      exit(0); 
     } 
    } 
    exit(0); 
} 
+2

由[tag:linux]替換了[tag:ubuntu],因爲在你的問題中沒有任何特定於Ubuntu的東西。 – 0xC0000022L

+2

確定可能的錯誤情況,在適當的時候在程序中爲它們設計有用的測試,然後用不同的退出代碼退出。也許給stderr一個錯誤信息。什麼更具體? – Minix

回答

2

在事實發生後,通過您的程序並修復所有那些缺少錯誤處理的錯誤將會非常痛苦。從一開始就編寫正確的代碼會更好!此外,你有更多的錯誤,而不僅僅是缺少錯誤處理。我沒有掃描所有的代碼,但乍看之下,我已經看到一個未初始化的局部變量的使用(在設置之前使用fork_pipes中的in)。任何啓用警告的體面編譯器都會發現這一點。

作爲對你問題的直接回答,你只需要經過並發現每一個系統調用或庫函數調用,它能夠返回錯誤,看看你是否檢查它們,並添加檢查,如果它們是還沒有。 forkmallocdup2 - 一切。

相關問題