Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- #include <time.h>
- #include <unistd.h>
- #include<sys/wait.h>
- #include <signal.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <stdbool.h>
- #define MSGSIZE 100
- //creating structure for message queue
- struct message_queue
- {
- long msg_type;
- char msg_txt[100];
- }message;
- bool loop = true;
- void interrupt_handler(int signal) {
- if(signal == SIGINT)
- {
- loop = false;
- }
- }
- //driver program
- int main() {
- //variables
- char *ptr1;
- char str[10];
- FILE *ptr;
- int returncode_msgrcv;
- //creating messsage queue
- key_t key = ftok("number.txt", 65);
- int msgid;
- msgid = msgget(key, 0666 | IPC_CREAT);
- message.msg_type = 10;
- while (loop == true) {
- //opening the file
- ptr = fopen("./numbers.txt","w+");
- //use of space after each number
- char delim[] = " ";
- // CONV //
- //random number generations
- srand(time(NULL));
- int num = 0;
- int sum = 0;
- int mean = 0;
- //child process
- int process1 = fork();
- if(process1 == 0) {
- wait(NULL);
- //getting ID
- // printf("Child process 1 ID:%d\n", getpid());
- //reading random numbers
- srand(time(NULL));
- for(int i=1; i<=10; i++) {
- fprintf(ptr, "%d ", rand()%11);
- }
- printf("\n");
- printf("Generated numbers in CONV: %d", ptr);
- printf("\n");
- fclose(ptr);
- fflush(NULL);
- return 0;
- //checking if message was sent into MQ
- if (msgsnd(msgid, &message, sizeof(message.msg_txt), 0) == -1){
- printf("message not sent\n");
- perror("msgsnd()");
- }
- }
- // LOG //
- //waiting queue
- wait(NULL);
- //new process
- int process2 = fork();
- if(process2 == 0) {
- if ((msgid = msgget(key, 0666 | IPC_CREAT)) == -1) {
- printf("could not reach Message queue\n");
- perror("msgget()");
- }
- returncode_msgrcv = msgrcv(msgid, &message, sizeof(message.msg_txt), message.msg_type, MSG_NOERROR|IPC_NOWAIT);
- if (returncode_msgrcv == -1) {
- printf("message not received\n");
- perror("msgrcv()");
- }else{
- printf("Child process 2 ID:%d\n",getpid());
- printf("\nWrote 10 integers to numbers.txt\n");
- }
- //opening the numbers generated in the file
- ptr = fopen("./numbers.txt","rb");
- if( fgets (str, 100, ptr)!=NULL ) {
- ptr1 = strtok(str, delim);
- }
- }
- // STAT //
- // int process3 = fork();
- // if (process3 == 0) {
- printf("\n");
- // printf("Child process 3 ID:%d\n",getpid());
- //
- //addition and average
- while(ptr1 != NULL) {
- num = atoi(ptr1);
- sum = sum + num;
- mean = sum/10;
- ptr1 = strtok(NULL, delim);
- }
- printf("Generated in REPORT: sum %d, mean %d \n", sum, mean);
- printf("\n");
- // }
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement