1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <errno.h>
#define MAX_SEQ 20
typedef struct{
unsigned int fib_sequence[MAX_SEQ];
int sequence_size;
}shared_data;
extern int errno;
void fib(shared_data* data);
int main(int argc, char *argv[])
{
unsigned int arg;
int segment_id;
struct shmid_ds* buf;
if (buf == NULL){
printf("wat\n");
}
if (argc == 1){
printf("You must input an argument\n");
exit(EXIT_FAILURE);
}
else if (argc > 2){
printf("You must input only 1 argument\n");
exit(EXIT_FAILURE);
}
else if (arg < 0){
printf("You must input number greater than or equal to 0\n");
exit(EXIT_FAILURE);
}
else if ((arg = atoi(argv[1])) == 0 && *argv[1] != '0'){
printf("You must input a number\n");
exit(EXIT_FAILURE);
}
if (arg > MAX_SEQ){
printf("Sorry, you must enter an argument less than %d\n", MAX_SEQ);
exit(EXIT_SUCCESS);
}
segment_id = shmget(IPC_PRIVATE, sizeof(shared_data), S_IRUSR | S_IWUSR);
if (segment_id < 0){
perror("shmget");
exit(EXIT_FAILURE);
}
shared_data* shared_memPtr = (shared_data*)shmat(segment_id, NULL, 0);
if(shared_memPtr < 0){
perror("shmat");
exit(EXIT_FAILURE);
}
shared_memPtr->sequence_size = arg;
if(shmctl(segment_id, IPC_STAT, buf) == -1){
perror("shmctl");
exit(EXIT_FAILURE);
}
printf("segment ID: %d \n", segment_id);
printf("Key: %d \n", buf->shm_perm.__key);
printf("Mode: %d \n", buf->shm_perm.mode);
printf("OwnerUID: %d \n", buf->shm_perm.uid);
printf("Size: %zu \n", buf->shm_segsz);
printf("No. of attaches: %d \n", (int)buf->shm_nattch);
pid_t pid = fork();
if (pid < 0){ /* error */
perror("fork");
exit(EXIT_FAILURE);
}
else if (pid == 0){ /* child */
fib(shared_memPtr);
exit(EXIT_SUCCESS);
}
else if (pid > 0){ /* parent */
int status;
if (wait(&status) < 0){ /* error */
perror("wait");
exit(EXIT_FAILURE);
}
if (WIFEXITED (status))
printf("Normal exit from child\n");
else
printf("Strange exit from child\n");
int n = shared_memPtr->sequence_size;
int i = 0;
for (i; i<n; i++){
printf("%d ", shared_memPtr->fib_sequence[i]);
}
printf("\n");
if(shmdt(shared_memPtr) < 0){
perror("shmdt");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
}
void fib(shared_data* data)
{
int n = data->sequence_size;
unsigned int fib1 = 1;
unsigned int fib2 = 1;
unsigned int temp = 0;
int i = 0;
for (i; i < n; i++){
data->fib_sequence[i] = fib1;
temp = fib2;
fib2 = fib1 + fib2;
fib1 = temp;
}
}
|