Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <unistd.h>
- #define SHMKEY ((key_t) 7890)
- #define MYSEED 1234
- typedef struct
- {
- int value;
- } shared_mem;
- shared_mem *counter; //shared variable
- int read_val(){
- return counter->value;
- }
- void write_val(int new_val){
- counter->value = new_val;
- }
- void sayHello(int id, int max){
- int i=0;
- int temp=0;
- for(i=0;i<max;i++){
- temp = read_val();
- temp = temp + 1;
- write_val(temp);
- }
- if(id == 0)
- printf ("\nThe child's count was %d\n",read_val());
- else
- printf ("\nThe father's count was %d\n",read_val());
- }
- int main(int argc, char *argv[])
- {
- int shmid; //shared memory Id
- int child1=0;
- int max=1000;
- int finished,status;
- int val;
- max = atoi(argv[1]); //obtaining the seed from the parameters, and turning it into a numeric value
- char *shmadd;
- shmadd = (char *) 0;
- if ((shmid = shmget (SHMKEY, sizeof(int), IPC_CREAT | 0666)) < 0)
- {
- perror ("shmget");
- val=1; //exit (1);
- }
- if ((counter = (shared_mem *) shmat (shmid, shmadd, 0)) == (shared_mem *) -1)
- {
- perror ("shmat");
- val=0; //exit (0);
- }
- counter->value = 0;
- if ((child1 = fork()) == 0){
- sayHello(child1,max);
- }
- if (child1 != 0){
- sayHello(child1,max);
- printf ("The child's id is %d \n",child1);
- finished = wait(&status); //Waiting for a child to finish and for getting its ID
- if(finished == child1){ //is child1?
- printf ("The child just finished with counter in %d\n",read_val());
- }
- if ((shmctl (shmid, IPC_RMID, (struct shmid_ds *) 0)) == -1)
- {
- perror ("shmctl");
- val=-1; //exit (-1);
- }
- printf ("\t\t End of simulation.\n");
- }
- return val;
- }
Add Comment
Please, Sign In to add comment