summaryrefslogtreecommitdiff
path: root/pgm7/child.c
blob: f9263e8b9e23ed3ee3203387e79d64c7565b0931 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
 * child.c
 *
 * Created by Matt Welsh, 1995
 *
 * Adapted by Adam Carpenter - acarpent - acarpenter@email.wm.edu
 * April 2017
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include "child.h"

/* Exec the named cmd as a child process, returning
 * two pipes to communicate with the process, and
 * the child's process ID */
int start_child(char *cmd, FILE **readpipe, FILE **writepipe) {
    int childpid, pipe1[2], pipe2[2];

    if ((pipe(pipe1) < 0) || (pipe(pipe2) < 0) ) {
       perror("pipe"); exit(-1);
    }

    if ((childpid = fork()) < 0) {
       perror("fork"); exit(-1);
    } else if (childpid > 0) {   /* Parent. */
       close(pipe1[0]); close(pipe2[1]);
       /* Write to child on pipe1[1], read from child on pipe2[0]. */
       *readpipe = fdopen(pipe2[0], "r");
       *writepipe = fdopen(pipe1[1], "w");
       setlinebuf(*writepipe);
       return childpid;

    } else { /* Child. */
       close(pipe1[1]); close(pipe2[0]);
       /* Read from parent on pipe1[0], write to parent on pipe2[1]. */
       dup2(pipe1[0],0); dup2(pipe2[1],1);
       close(pipe1[0]); close(pipe2[1]);

       if (execlp(cmd, cmd, NULL) < 0)
          perror("execlp");
       /* Never returns */
    }
    return 0;  // to keep the compiler happy
}

void i_am_the_master_commander(char *handle, char *opphandle, FILE **writeTo) {
    /*
     * Look, don't touch.
     */

    if (strcmp(handle, "Adam") == 0) {
        fprintf(*writeTo, ".statusFrame.playerStatus configure -fg blue\n");
    }
    else if (strcmp(handle, "Dan") == 0) {
        fprintf(*writeTo, ".statusFrame.playerStatus configure -fg red\n");
    }
    else if (strcmp(handle, "Amy") == 0) {
        fprintf(*writeTo, ".statusFrame.playerStatus configure -fg \"light sea green\"\n");
    }

    if (strcmp(opphandle, "Adam") == 0) {
        fprintf(*writeTo, ".statusFrame.opponentStatus configure -fg blue\n");
    }
    else if (strcmp(opphandle, "Dan") == 0) {
        fprintf(*writeTo, ".statusFrame.opponentStatus configure -fg red\n");
    }
    else if (strcmp(opphandle, "Amy") == 0) {
        fprintf(*writeTo, ".statusFrame.opponentStatus configure -fg \"light sea green\"\n");
    }

}