- 論壇徽章:
- 0
|
本帖最后由 lansunlong 于 2011-04-28 13:08 編輯
一個(gè)簡(jiǎn)單的C寫的shell程序,用管道實(shí)現(xiàn)輸入的命令,測(cè)試命令為 /bin/ls -l / | /bin/more ,但是結(jié)果輸出不是期望的輸出,
代碼如下,即附件中的內(nèi)容,請(qǐng)大家?guī)兔φ艺覇栴}哦
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#define MAX_HISTORY 12
#define MAXBUF 100
//管道初始化宏定義
#define NO_PIPE -1//標(biāo)識(shí)管道關(guān)閉
#define NO_READ 0//標(biāo)識(shí)管道端為讀端
#define NO_WRITE 1//標(biāo)識(shí)管道端為寫端
int status;
//--文件描述符
int fd[10][2];
//管道命令處理函數(shù)
int pipel(char *input, int input_len)
{
char *pargtem[10][4];
char buf[MAXBUF];
strcpy(buf,input);
input_len ++;
char *input1 = (char *)malloc(sizeof(char)*(input_len));
buf[input_len-1] = ' ';
strcpy(input1, buf);
int i=0;
//初始化文件描述符
for(i=0; i<10;i++)
{
fd[NO_READ] = NO_PIPE;
fd[NO_WRITE] = NO_PIPE;
}
//解析命令
// int j=1;
int m=0;//標(biāo)識(shí)管道中的新命令
int j=0;//標(biāo)識(shí)管道命令計(jì)數(shù)
int k=0;//標(biāo)識(shí)命令參數(shù)計(jì)數(shù)
for(i=0; i<input_len; i++)
{
if(input1 == '\0' || input1 == ' ')
{
if(m == 0)
continue;
else
{
buf[m++] = '\0';
pargtem[j][k] = (char *)malloc(sizeof(char)*m);
strcpy(pargtem[j][k++], buf);
m=0;
}
}
else if(input1 == '|')
{
if(m == 0)
{
pargtem[j][k] = NULL;
j++;k=0;
}
else
{
buf[m++] = '\0';
pargtem[j][k] = (char *)malloc(sizeof(char)*m);
strcpy(pargtem[j][k++], buf);
pargtem[j][k] = NULL;
m=0;j++;k=0;
}
}
else
buf[m++] = input1;
}
free(input1);
int li_cmd = j;//解析命令完成,解析完成后的命令存儲(chǔ)在二維數(shù)組pargtem中,命令個(gè)數(shù)為li_cmd
//建立管道
for(i = 0; i<=li_cmd; i++)
{
if(pipe(fd) == -1)
{
printf("Can not open pipe!\n");
return 0;
}
}
//初始化程序的輸入輸出端到管道的讀寫端
int pid[100];
for(i=0; i< li_cmd; i++)
{
if( i == 0)
{
if((pid[0] = fork()) < 0)
{
perror("Fork failed");
exit(errno);
}
if(!pid[0])
{
dup2(fd[0][1], 1);
close(fd[0][0]);
close(fd[0][1]);
if(execvp(pargtem[0][0], pargtem[0]) == -1)
{
perror("Execvp failed");
exit(errno);
}
}
else
{
close(fd[0][0]);
close(fd[0][1]);
}
}
else
{
if((pid = fork()) < 0)
{
perror("Fork failed");
exit(errno);
}
if(!pid)
{
dup2(fd[1], fd[i-1][0]);
close(fd[0]);
close(fd[1]);
if(execvp(pargtem[0], pargtem) == -1)
{
perror("Execvp failed");
exit(errno);
}
}
else
{
close(fd[0]);
close(fd[1]);
}
}
}
dup2(fd[li_cmd][0], 0);
close(fd[li_cmd][1]);
close(fd[li_cmd][0]);
if(execvp(pargtem[0], pargtem) == -1)
{
perror("Execvp failed");
exit(errno);
}
printf("End\n");
return 0;
}
int main()
{
char *input = "/bin/ls -l / | /bin/more";
int input_len;
input_len = strlen(input);
pipel(input, input_len);
return 0;
} |
-
捕獲.JPG
(46.92 KB, 下載次數(shù): 24)
下載附件
2011-04-28 13:05 上傳
運(yùn)行結(jié)果
-
-
pipel_test.zip
2011-04-28 13:08 上傳
點(diǎn)擊文件名下載附件
1.21 KB, 下載次數(shù): 13
代碼
|