Untitled
By: a guest | Jan 31st, 2009 | Syntax:
None | Size: 2.00 KB | Hits: 152 | Expires: Never
/*
PUBLIC DOMAIN
Fuck GNU, Fuck Creative Commons, Fuck BSD.
Attribution are for tards.
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
const key_t SHM_KEY = 0x42385; /* random number known by all processes, somehow */
const int SHM_SIZE = 16*1024*1024; /* 16MB get allocated.. */
const int SHM_FLAGS = IPC_CREAT | 0666; /* It does not work unless you supply IPC_CREAT (!?),
0666 are the permissions. */
/* Allocate does not allocate anything, it just returns an *identifier* to be used by attach() */
int allocate()
{
int shmid;
if (( shmid = shmget( SHM_KEY, SHM_SIZE, SHM_FLAGS )) == -1 )
{
perror("shmget: shmget failed");
exit(1);
}
return shmid;
}
/* Returns a pointer to the shared memory, takes an identifier created by shmget() or allocate() */
void *attach(int shmid)
{
void *shm;
if(( shm = shmat( shmid, NULL, 0 )) == (void*) -1 )
{
perror("shmat");
exit(1);
}
return shm;
}
/* Child writes "Hello world.\n" to the shared memory, sleeps for one second and the dies. */
void child()
{
char *str = "Hello world.\n";
void *shared_mem;
shared_mem = attach( allocate() );
strncpy( shared_mem, str, strlen(str)+1 );
sleep(1);
printf("The child has written to shared memory. Goodbye ;)\n");
_exit(0);
}
/* Mother reads from the shared memory after 2 seconds and prints the content. */
void mother()
{
void *shared_mem;
shared_mem = attach( allocate() );
sleep(2);
printf("Mother reads from shared memory: %s", shared_mem);
exit(0);
}
/* Creates two processes. */
void forkoff()
{
if( fork() == 0 )
child();
else mother();
}
/* bla bla blaa bla-bla blabla blabla-bla bla */
int main()
{
forkoff();
return -1; /* should never return */
}