Question

I have simple program:

#include <stdio.h>

int a = 5;

int
main(void)
{
    while(1)
    {
        int i;
        sleep(1);
        printf("%p %i\n", &a, a);
    }
    return 0;
}

Output (Ubuntu x64):

0x601048 5
0x601048 5
0x601048 5
0x601048 5

I was learning about pointers in C and I already know that you can use memcpy to write data wherever (almost) you want within virtual memory of process. But, is it possible to modify value of int a, placed at 0x601048 address, by using another application(which is of course using its own virtual memory)? How to do this? I'm interested in solutions only for C.

Was it helpful?

Solution

It is not easily possible (to share virtual memory between two different processes on Linux). As a first approximation, code as it if was not possible.

And even if you did share such memory, you'll get into synchronization issues.

You really should read books like Advanced Linux Programming. They have several chapters on that issue (which is complex).

Usually, if you really want to share memory, you won't share some memory on the call stack, but you would "reserve" some memory zone to be later shared.

You could read a lot more about

  • pthread-s (e.g. read this pthread tutprial)

  • shared memory segments set up with mmap(2) using MAP_SHARED

  • low level debugging facilities using ptrace(2) notably PTRACE_PEEKDATA

  • old SysV shared memory using shmat(2)

  • Posix shared memory (see shm_overview(7)...) using shm_open(2)

  • /proc/ file system proc(5) e.g. /proc/$PID/mem ; I strongly suggest to look at file:///proc/self/maps at first in your browser and to read more till you understand what that is showing you. (you could mmap some other's process /proc/$PID/mem ....)

  • /dev/mem (the physical RAM) see mem(4)

  • loading a kernel module doing insane tricks.

I strongly advise against playing such dirty memory tricks for a beginner. If you insist, be prepared to break your system and backup it often. Don't play such tricks while a Linux novice.

Often you'll need root privileges. See capabilities(7)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top