|
#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();
|
}
|