On 7 Apr 2008 at 19:11,
ar**********@gmail.com wrote:
Hi all,
I have specific question about usage of extern. I want to share a
single variable say int a; across multiple files.
I would define it in file1.c as
int a=0;
int main()
{
.........
a= 20;
..........
}
In another file2.c I would use it as,
int main()
{
extern int a;
................
printf("value of a=%d\n", a);
..................
}
Is this usage right. If yes, how do I run these as two separate
processes so that value changed in file1 is always reflected in file2
whenever it is used in fil2.c. How do I link these two processes put
it in another way.
You need to investigate your system's shared memory features. On POSIX
you can used the shm* functions and mmap - here's an extremely simple
example:
/* server.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#define MESSAGE "Hello world\n"
#define PATH "/foobar"
#define SIZE 100
int main(void)
{
int shmfd;
char *msg;
if((shmfd = shm_open(PATH, O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG)) < 0)
abort();
ftruncate(shmfd, SIZE);
msg = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
if(!msg)
abort();
strcpy(msg, MESSAGE);
return 0;
}
/* client.c */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#define PATH "/foobar"
#define SIZE 100
int main(void)
{
int shmfd;
char *msg;
if( (shmfd = shm_open(PATH, O_RDWR, S_IRWXU | S_IRWXG)) < 0)
abort();
msg = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
if (!msg)
abort();
printf("%s", msg);
if (shm_unlink(PATH))
abort();
return 0;
}
$ make server client LDLIBS=-lrt
cc server.c -lrt -o server
cc client.c -lrt -o client
$ ./server
$ ./client
Hello world