2017-02-27 22 views
0

我在做流程管理實踐的一些在Linux和如何使用系統調用和子和父進程之間的通信。我需要實現一個管道來獲得由子進程所提供的字符串,它是目錄列表作爲字符串,並將其傳遞給父進程來計數該字符串的行數,並通過這樣做,發現在該目錄中的文件數。我所面臨的問題是在這裏:將execl命令(即目錄列表)的結果輸出到父進程?

錯誤:初始化失敗,以確定的 'dirFileList' 炭dirFileList [] =讀取大小(隧道[0],buf中,MAX_BUF)

另外我的代碼是下面向下:

#define die(e) do { fprintf(stderr, "%s\n", e); exit(EXIT_FAILURE); } while (0); 
#define MAX_BUF 2024 
int main() 
{ 
const char *path = (char *)"/";        /* Root path */ 
const char *childCommand = (char *)"ls |";     /* Command to be executed by the child process */ 
const char *parentCommand = (char *)"wc -l";     /* Command to be executed by the parent process */ 

int i = 0;             /* A simple loop counter :) */ 
int counter = 0;            /* Counts the number of lines in the string provided in the child process */ 
int dirFileNum;            /* Keeps the list of files in the directory */ 
int tunnel[2];            /* Defining an array of integer to let the child process store a number and parent process to pick that number */ 
pid_t pID = fork(); 
char buf[MAX_BUF];           /* Fork from the main process */ 


if (pipe(tunnel) == -1)          /* Pipe from the parent to the child */ 
    die("pipe died."); 

if(pID == -1)            /* Check if the fork result is valid */ 
{ 
    die("fork died."); 
} 
else if(pID == 0)           /* Check if we are in the child process */ 
{ 
    dup2 (tunnel[1], STDOUT_FILENO);       /* Redirect standard output */     
    close(tunnel[0]); 
    close(tunnel[1]); 
    execl(childCommand, path);        /* Execute the child command */ 
    die("execl died."); 
} 
else               /* When we are still in the main process */ 
{ 
    close(tunnel[1]); 
    char dirFileList[] = read(tunnel[0],buf,MAX_BUF);     /* Read the list of directories provided by the child process */ 
    for(i;i<strlen(dirFileList);i++)       /* Find the number of lines in the list provided by the child process */ 
     if(dirFileList[i] == '\n') 
      counter++; 

    printf("Root contains %d files.", counter);    /* Print the result */ 
    wait(NULL);            /* Wait until the job is done by the child process */ 

}  

return 0;  
} 
+0

我希望你僅僅使用'ls'作爲教育範例命令。有充分的理由喜歡'READDIR()'和'STAT()'優先於解析'ls' ... –

+0

@TobySpeight是的,先生的輸出!我很想知道這些命令是如何工作的。感謝評論,我會測試你的建議。 – aligholamee

回答

0

如果您想向我們展示了整個錯誤消息,我們會看到它引用這條線:

char dirFileList[] = read(tunnel[0],buf,MAX_BUF); 

你不能聲明一個不確定的ARRA你喜歡那樣。如果你讀的read(2)手冊頁,你會看到返回值是

On success, the number of bytes read ...
On error, -1 ...

所以,你要像

int bytes_read = read(...); 
if (bytes_read < 0) { 
    perror("read"); 
    exit(1); 
} 

一些額外的審覈(你沒要求,但可能有啓發性):

請勿將字符串文字強制轉換爲char*,尤其是當您將其分配給const char*變量時。

而不是隻打印在錯誤固定的消息,可以說已成立errno如果使用perror()一個電話後,更豐富的信息 - 請看我上面的示例。

die()可以實現的功能,這將使它更容易調試和比宏正確使用。

相關問題