Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/shm.h>
- #include <sys/stat.h>
- #include <stdlib.h>
- int powmod(int, int, int);
- int powmodf(int, int,int);
- int p = 103;
- int g = 101;
- int S_a ;
- int S_b ;
- int T_a ;
- int T_b ;
- int main ()
- {
- int pid1; //Alice
- int pid2; //Bob
- int pid; //Parent
- char *shared_memory;
- const int segment_size =4096;
- int segment_id;
- segment_id = shmget(IPC_PRIVATE, segment_size, S_IRUSR | S_IWUSR);
- shared_memory = (char *) shmat(segment_id, NULL, 0);
- printf("\n Qshrdmem: Using Shared Memory for IPC \n");
- printf("Diffie-Hellman Parameters p=%d and g=%d\n", p,g);
- printf("Parent: pid=%d \n", getpid());
- pid1 = fork(); //alice
- if (pid1 == 0 )
- {
- printf ("Alice: pid=%d, ", getpid());
- printf ("My Parent pid=%d\n", getppid());
- S_a = rand() % 100 + 1;
- printf("\nAlice's random secret = %d", S_a);
- T_a = powmod(S_a, g , p );
- printf("Alice has a T_a of: %d ", T_a);
- sprintf(shared_memory, T_a);}
- else //create Bob
- {
- pid2=fork();
- if (pid2==0)
- {
- usleep(10000);
- printf ("Bob: pid=%d, ", getpid());
- printf ("My Parent pid=%d\n", getppid());
- S_b = rand() % 100 + 1;
- printf("\nAlice's random secret = %d", S_b);
- T_b = powmod(S_b, g , p );
- printf("Alice has a T_b of: %d ", T_b);
- sprintf(shared_memory, T_b);
- }}
- else //Parent code
- {
- usleep(10000);
- printf("Parent: pid=%d \n", getpid());
- printf("Parent view of shared memory: %s\n", shared_memory);}
- //detach memory segment
- if (shmdt(shared_memory) == -1)
- {
- fprintf(stderr, "unable to detach\n");}
- //remove shared memory segment
- shmct1(segment_id,IPC_RMID, NULL);
- return 0;}
- powmod (int a, int b, int n)
- {
- int i;
- int res = a;
- for(i=1; i<b;i++)
- res = (res * a) % n;
- return res;
- }
- int powmodf(int a,int b, int n){
- int res=1;
- while (b)
- {
- if (b % 2) { res = (res * a) % n; }
- a = (a * a) % n;
- b /= 2;
- }
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment