#include "usg_common.h" #include "usg_typedef.h" #include #include int open_file(char *filename) { int fd = open(filename, O_CREAT | O_APPEND | O_RDWR , FILE_MODE); return fd; } 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(int fd, int start, int end) { write_to_file_with_no_lock(fd, start, end); //write_to_file_with_lock(fd, start, end); } void read_from_file(int fd) { lseek(fd, 0, SEEK_SET); char buf[1024]; while(read( fd, buf, 1024) > 0) { printf("%s", buf); } } int main() { int fd = open_file("test.txt"); int status, i = 0, processors = 4, scale = 100; pid_t productors[processors], consumers[processors]; pid_t pid; fd = open_file("stand.txt"); write_to_file_with_no_lock(fd, 0, processors * scale); read_from_file(fd); for ( i = 0; i < processors; i++) { if ((productors[i] = fork()) == 0) /* Child runs user job */ { fd = open_file("test.txt"); int start = i * scale, end = i * scale + scale; printf("======start=%d, end=%d\n", start, end); write_to_file(fd, start, end); sleep(1); exit(0); } } // 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 = "./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"); close(fd); }