Search code examples
csedpipeforkexec

Using sed with the execvp to cut part of stout. C


I'm using a function that echo a string and redirect output to a sed input in c. If i echo a string like "hello: bye bye", i need to cut everything before the ":". So i buildt a function that fork and pipe for this but sed won't recognize my regex:

void sender (char * str_ ,char * pipe_ ,char **args_) {
    int fd[2];
    int pid;
    char* cmd1[] = {"echo", str_,NULL};
    char* sed[] = {"sed","'[^:]*$'",NULL};
    int status;

    pid = fork();
    if (pid == 0) {
        if(pipe(fd) < 0){
            exit(100);
        }
        pid = fork();
        if (pid == 0) {
            close(fd[0]);
            dup2(fd[1], 1);
            close(fd[1]);
            execvp(cmd1[0], cmd1);
            printf("Error in execvp1\n");
        }else{
            close(fd[1]);
            wait(&status);
            dup2(fd[0],0);
            close(fd[0]);
            dup2(1,2);
            execvp(sed[0],sed);
            printf("Error in execvp2\n");
        }
    }
    else{
        close(fd[0]);
        close(fd[1]);
        wait(&status);
        wait(&status);
    }
}

The output is error for every line read because of sed:expression -e #1, character 1: unknown command: `''


Solution

  • #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/wait.h>
    
    void pipe_exec(int pfd[], char *cmd_args[], int redirect_output)
    {
        printf("%s, pid %d\n", cmd_args[0], getpid());
    
        if (redirect_output)
            dup2(pfd[1], 1);
        else
            dup2(pfd[0], 0);
    
        close(pfd[0]);
        close(pfd[1]);
        execvp(cmd_args[0], cmd_args);
        printf("Error in execvp\n");
        exit(1);
    }
    
    void sender(char *str_, char *unused1, char **unused2)
    {
        int status, pid, fd[2];
        char *cmd1[] = { "echo", str_, NULL };
        char *sed[] = { "sed", "s/[^:]*://", NULL };
    
        if (pipe(fd) < 0)
            exit(100);
    
        pid = fork();
        if (pid == 0)
            pipe_exec(fd, cmd1, 1);
    
        pid = fork();
        if (pid == 0)
            pipe_exec(fd, sed, 0);
    
        close(fd[0]);
        close(fd[1]);
        wait(&status);
        wait(&status);
    }
    
    int
    main(void)
    {
        sender("hello: bye bye", NULL, NULL);
        return (0);
    }