我在做流程管理實踐的一些在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;
}
我希望你僅僅使用'ls'作爲教育範例命令。有充分的理由喜歡'READDIR()'和'STAT()'優先於解析'ls' ... –
@TobySpeight是的,先生的輸出!我很想知道這些命令是如何工作的。感謝評論,我會測試你的建議。 – aligholamee