IO交互题测试器

· · 科技·工程

参考 https://notes.sshwy.name/Interactive-Prob-Judger/,本文优化了其代码实现。

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


int main(int argc, char ** argv){
    if(argc != 3) {
        fprintf(stderr, "Usage: %s [command1] [command2]\n", argv[0]);
        return 0;
    }

    int p[2][2];
    if(pipe(p[0]) == -1 || pipe(p[1]) == -1) 
        return fprintf(stderr, "fail to create pipe\n"), 1;

    pid_t id = fork();

    if(id < 0) return fprintf(stderr, "error fork\n"), 1;

    bool s = id == 0;

    if (dup2(p[ s][0], fileno(stdin )) == -1 ||
        dup2(p[!s][1], fileno(stdout)) == -1)
        return fprintf(stderr, "error dup2"), 1;

    char *v[] = {argv[2 - s], NULL};
    char *e[] = {NULL};
    execve(argv[2 - s], v, e);
    return 0;
}