Загрузка данных


#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

pid_t start(const char *file, const char *arg, int mode)
{
    pid_t pid = fork();

    if (pid == 0)
    {
        if (mode == 'p')
        {
            char *args[] = {(char *)file, (char *)arg, NULL};
            execvp(file, args);
        }
        else
        {
            execlp(file, file, arg, (char *)NULL);
        }
        _exit(127);
    }
    return pid;
}

int result(pid_t pid, const char *file)
{
    int st;

    if (pid < 0 || waitpid(pid, &st, 0) == -1)
    {
        return 1;
    }
    if (WIFEXITED(st))
    {
        if (WEXITSTATUS(st) == 0)
        {
            printf("%s: exit 0 ok\n", file);
        }
        else
        {
            printf("%s: exit %d fail\n", file, WEXITSTATUS(st));
        }
    }
    else if (WIFSIGNALED(st))
    {
        printf("%s: signal %d\n", file, WTERMSIG(st));
    }
    return 0;
}

int main(int argc, char **argv)
{
    pid_t first, second;
    int mode, err = 0;

    if (argc != 6 || (argv[5][0] != 'p' && argv[5][0] != 's') || argv[5][1] != '\0')
    {
        return 1;
    }
    mode = argv[5][0];
    first = start(argv[1], argv[2], mode);
    if (first < 0)
    {
        return 1;
    }
    if (mode == 's')
    {
        err |= result(first, argv[1]);
    }
    second = start(argv[3], argv[4], mode);
    if (second < 0)
    {
        if (mode == 'p')
        {
            result(first, argv[1]);
        }
        return 1;
    }
    if (mode == 'p')
    {
        err |= result(first, argv[1]);
    }
    err |= result(second, argv[3]);
    return err;
}