管道

it2022-05-09  60

https://segmentfault.com/a/1190000009528245

 

#include <stdio.h>#include <stdlib.h>#include <unistd.h>

#define CUR_PATH_LEN 100#define CMD_LEN 10000

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; }

dup2(pipes_fd_prev[0], 0); dup2(pipes_fd_next[1], 1);

close(pipes_fd_prev[0]); close(pipes_fd_next[1]);

execl(path, name, args, NULL);error:

return ;}

//check syntax of cmd//TODOint check_cmd(char* cmd){ int ret = -1;

//set this 'ret' to 0 before implement this function. ret = 0;

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;}

转载于:https://www.cnblogs.com/Dream-Chaser/p/9339247.html


最新回复(0)