Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <stdlib.h>
- void process_child(const char *command, char *parameters[])
- {
- execvp(command, parameters);
- }
- char raw_commands[256][256];
- char commands[256][256];
- char *parameters[256][256];
- int n_commands;
- int main(int argc, char **argv)
- {
- if (argc != 2) {
- printf("Usage: main \"cmd1 cmd_params.. | cmd2 cmd_params... \"");
- return 0;
- }
- int i, j, h, k;
- for (i=0; i<256; i++) {
- for (j=0; j<256; j++) {
- parameters[i][j]=(char*)malloc(256*sizeof(char));
- }
- }
- i=0; j=0; h=0; k=0;
- int size=strlen(argv[1]);
- while (i<size) {
- if ((argv[1][i]==' ') && (j==0)) {
- j=1;
- h=0;
- }
- else if ((argv[1][i]==' ') && (j==1)) {
- k++;
- h=0;
- }
- else if (argv[1][i]=='|') {
- n_commands++;
- j=0;
- h=0;
- k=0;
- }
- else if (j==0) {
- commands[n_commands][h]=argv[1][i];
- h++;
- }
- else {
- parameters [n_commands][k][h]=argv[1][i];
- h++;
- }
- i++;
- }
- int fd_pipe[2]; // 0 -- input, 1 -- output
- for (i = 0; i < n_commands; ++i) {
- pipe(fd_pipe);
- int code = fork();
- if (!code) {
- // child
- // if last command
- if (i + 1 == n_commands) {
- close(fd_pipe[1]);
- } else {
- dup2(fd_pipe[1], 1); // output to created pipe
- }
- close(fd_pipe[0]);
- process_child(commands[i], parameters[i]);
- return 0;
- } else {
- // parent
- if (i + 1 == n_commands) {
- // last command
- close(fd_pipe[0]);
- } else {
- dup2(fd_pipe[0], 0); // receive input from pipe
- }
- close(fd_pipe[1]);
- }
- }
- for (i = 0; i < n_commands; ++i) {
- wait(NULL);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement