synchro.c

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

#include <unistd.h>
#include <errno.h>

#include "utils.h"

int main(int argc, char *argv[])
{
    int left_count = 0;
    char *args_left[argc];
    int right_count = 0;
    char *args_right[argc];

    int i;
    for (i = 1; i < argc ; i ++) {
        if (strcmp("--", argv[i]) == 0) break;
        args_left[left_count ++] = argv[i];
    }
    args_left[left_count] = NULL;


    for (i = i + 1; i < argc ; i ++) {
        args_right[right_count ++] = argv[i];
    }
    args_right[right_count] = NULL;

    if (left_count == 0 || right_count == 0) {
        fprintf(stderr, "Syntax: %s <prog1> [args ...] -- <prog2> [args ...]\n", argv[0]);
    }

    int fds[2];
    pipe(fds);
    switch(fork()) {
        case -1: exit_if(1, "Can't fork");
        case 0:
                 close(fds[STDOUT_FILENO]);
                 dup2(fds[STDIN_FILENO], STDIN_FILENO);
                 execvp(args_right[0], args_right);
                 perror(args_right[0]);
                 break;
        default:
                 close(fds[STDIN_FILENO]);
                 dup2(fds[STDOUT_FILENO], STDOUT_FILENO);
                 execvp(args_left[0], args_left);
                 perror(args_left[0]);
                 break;
    }
    return EXIT_FAILURE;
}