Hi,
I'm trying a few things in C, but cannot advance now.
This program should read what it written in the shared memory if does not take any arguments. However if arguments are passed it should write what is passed into the memory. I can make it work if just pass one argument, but it crashes if more.
Any help, please! :)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main(int argc, char *argv[])
{
key_t key;
int shmid;
char *data;
if ((key = ftok("mempart1.c", 0)) == -1) {
perror("ftok");
exit(1);
}
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
perror("shmget");
exit(1);
}
data = shmat(shmid, NULL, 0);
if (data == (char *)(-1)) {
perror("shmat");
exit(1);
}
if (argc >= 2) {
strcpy(data, argv[1]);
int i = 2;
while(i <= argc){
strcat(data, argv[i]);
}
} else
printf("Data written: \"%s\"\n", data);
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
return 0;
}
Ty! ;)