Skip to content

Instantly share code, notes, and snippets.

@dulimarta
Last active October 22, 2020 00:43
Show Gist options
  • Save dulimarta/4a361b3deecf6e522cef5c561763a484 to your computer and use it in GitHub Desktop.
Save dulimarta/4a361b3deecf6e522cef5c561763a484 to your computer and use it in GitHub Desktop.
CS452 Lab06 - Sample 3
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/mman.h>
typedef struct {
int arr[2];
} shared_info;
int main (int argc, char*argv[]) {
int status;
long int i, loop = 0;
shared_info *shr;
int shmId;
char shmName[50];
pid_t pid;
sprintf(shmName, "swap-%d", getuid());
/*
* TODO: get value of loop variable(from command - line
* argument
*/
shmId = shm_open (shmName, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
ftruncate(shmId, sizeof(shared_info));
shr = mmap(NULL, sizeof(shared_info), PROT_READ|PROT_WRITE, MAP_SHARED, shmId, 0);
shr->arr[0] = 0;
shr->arr[1] = 1;
pid = fork ();
if (pid == 0) {
for (i = 0; i < loop; i++) {
/*
* TODO: swap the contents of shr->arr[0] and shr->arr[1]
*/
}
munmap (shr->arr, 2 * sizeof(long int));
exit (0);
}
else {
for (i = 0; i < loop; i++) {
/*
* TODO: swap the contents of shr->arr[1] and shr->arr[0]
*/
}
}
wait (&status);
printf ("values: %d\t%d\n", shr->arr[0], shr->arr[1]);
munmap (shr->arr, sizeof(shared_info));
shm_unlink(shmName);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment