https://segmentfault.com/a/1190000009528245shell
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>segmentfault
#define CUR_PATH_LEN 100
#define CMD_LEN 10000this
void run_cmd(char* path, char* name, char* args, int* pipes_fd_prev, int* pipes_fd_next)
{
if (NULL == pipes_fd_prev || NULL == pipes_fd_next)
{
goto error;
}ip
dup2(pipes_fd_prev[0], 0);
dup2(pipes_fd_next[1], 1);get
close(pipes_fd_prev[0]);
close(pipes_fd_next[1]);input
execl(path, name, args, NULL);
error:cmd
return ;
}it
//check syntax of cmd
//TODO
int check_cmd(char* cmd)
{
int ret = -1;pip
//set this 'ret' to 0 before implement this function.
ret = 0;io
return ret;
}
int main(int argc, char* argv[])
{
char cmd[CMD_LEN];
printf("Welcome to use this pipeshell.\n");
while(1)
{
int cmd_act_len;
int count_pipe_line = 0;
int *pipes_fd;
int current_path[CUR_PATH_LEN];
//print promotion of this shell
getcmd(current_path, CUR_PATH_LEN);
current_path[CUR_PATH_LEN-1] = 0;
printf("%s $ \n", current_path);
//read cmd from input of keyboard
cmd_act_len = read(0, cmd, CMD_LEN);
// check syntax of cmd
asset(check_cmd(cmd) == 0);
if (0 > cmd_act_len)
{
perror("fail to read\n");
exit(EXIT_FAILURE);
}
//count the number of pipe
for (int i = 0; i < cmd_act_len; i++)
{
if (cmd[i] == '|')
{
count_pipe_line++;
}
}
//create pipes_fd and pipes
pipes_fd = (int*) malloc(sizeof(int) * 2 * count_pipe_line);
for (int i = 0; i < count_pipe_line; i++)
{
pipe(&pipes_fd[i * 2]);
}
for (int i = 0; i < count_pipe_line + 1; i++)
{
pid_t pid = fork();
if (pid < 0)
{
perror("fail to read\n");
exit(EXIT_FAILURE);
}
if (pid > 0)
{
//parent
}
else
{
//child
}
}
//free pipes_fd array
free(pipes_fd);
}
return 0;}