wangzhengquan
2020-06-11 5c9cbf5ea152f501ae976e0e0b4ef5ee98afdfba
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
 
#include "usg_common.h"
#include "usg_typedef.h"
#include <iostream> // not needed for many systems
#include <fstream>
#include <string>
 
using namespace std;
 
 
// void write_to_file_with_no_lock(int fd, int start, int end) {
//     int i;
//     char buf[1024];
//     for(i = start;  i< end; i++) {
//         sprintf(buf, "%d\n", i);
//         if (write(fd,  buf,  strlen(buf)) == -1) {
//              err_exit(errno, "write_to_file");
//         }
 
//     }
 
// }
 
// void write_to_file_with_lock(int fd, int start, int end) {
//     int i;
//     char buf[1024];
//     for(i = start; i< end; i++) {
//         sprintf(buf, "%d\n", i);
 
//         if (flock(fd , LOCK_EX) == -1) {
//             err_exit(errno, "LOCK_EX");
//         }
//         if (write(fd,  buf,  strlen(buf)) == -1) {
//              err_exit(errno, "write_to_file");
//         }
//         if (flock(fd, LOCK_UN) == -1)
//             err_exit(errno, "LOCK_UN");
 
//     }
 
// }
 
 
void write_to_file(ofstream &fout, int start, int end) {
    int i;
    for(i = start;  i< end; i++) {
         fout << i << endl;
 
    }
    //write_to_file_with_lock(fd, start, end);
}
 
void read_from_file(ifstream &fin) {
    fin.seekg(0);
    char buf[1024];
    while(fin.getline(buf, 1024)) {
        printf("%s\n", buf);
    }
 
}
 
int main() {
    ofstream fout;
    ifstream fin("stand.txt");
 
 
 
     
    int status, i = 0, processors = 4, scale = 100000;
    pid_t productors[processors], consumers[processors];
    pid_t pid;
    ofstream fouts[processors];
 
    fout.open("stand.txt", ios_base::app);
    
    write_to_file(fout, 0,  processors * scale);
 
    fout.close();
    //read_from_file(fin);
 
    
 
    for ( i = 0; i < processors; i++) {
        if ((productors[i] = fork()) == 0)     /* Child runs user job */
        {
           fouts[i].open("test.txt", ios_base::out | ios_base::app);
           int start = i * scale, end = i * scale + scale;
           printf("======start=%d, end=%d\n", start, end);
           write_to_file(fouts[i], start, end);
           exit(0);
        }
    }
 
 
    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");
    fout.close();
    fin.close();
}