wangzhengquan
2021-02-02 0a94312fe0cb1fa2bb971919fb8bfce7f7a7ad73
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
76
77
78
#include "test.h"
extern char **environ; 
using namespace std;
 
 
void sigint_handler(int sig) {
    // mm_destroy();
    exit(0);
}
 
int main() {
    signal(SIGINT,  sigint_handler);
    remove("p.txt");
    remove("c.txt");
    int status, i = 0, processors = 4, scale = 100000;
    pid_t productors[processors], consumers[processors];
    pid_t pid;
 
    // const char *cmd = "rm -f p.txt c.txt";
    // if (execl("/bin/sh", "sh", "-c", cmd, 0) < 0)
 //    {
 //        err_exit(errno, "consumers execve");
 //    }
 
    for ( i = 0; i < processors; i++) {
        if ((productors[i] = fork()) == 0)     /* Child runs user job */
        {
           // char start[100];
           // char end[100];
           // itoa(, start);
           // itoa(, end);
           int start = i * scale, end = i * scale + scale;
           char cmd[1000];
           // char  *argv[] = {"productor", start, end, NULL };
           // const char *cmdfmt = "./single_productor %d %d >> p.txt";
           const char *cmdfmt = "./single_productor %d %d >> p.txt";
           sprintf(cmd, cmdfmt, start, end);
            if (execl("/bin/bash", "bash", "-c", cmd, 0) < 0)
            {
                 
                err_exit(errno, "productor execve");
            }
        }
    }
    for ( i = 0; i < processors; i++) {
        if ((consumers[i] = fork()) == 0)     /* Child runs user job */
        {
                
           // char cmd[1000];
           // char  *argv[] = {"productor", start, end, NULL };
            // const char *cmd = "./single_consumer  >> c.txt";
            const char *cmd = "./single_consumer >> c.txt";
            if (execl("/bin/bash", "bash", "-c", cmd, 0) < 0)
            {
                err_exit(errno, "consumers execve");
            }
        }
    }
 
    while ((pid = waitpid(-1, &status, 0)) > 0) {
        if(WIFEXITED(status)) {
            //fprintf(stderr, "child %d terminated normally with exit status=%d\n", pid, WEXITSTATUS(status));
        }else
            fprintf(stderr, "child %d terminated abnormally\n", pid);
    }
 
    if (errno != ECHILD)
        perror("waitpid error");
 
 
    //mm_destroy();
    
 
    
 
    return 0;
 
}