简体   繁体   中英

How to pass mmap to execve function in C?

I am coding in Linux and trying to do some task by executing another program.

The master must execute slaves to make some word search on some input files (1 file per slave). After all searching done, master will write the matchings lines found by the slave processes to an output file. I am trying to make the communication between master and slaves using named shared memory.

I need to pass my mmap call's pointer in the master's main to the other program and get it in there but I can not, because its type is not matching.

If I use semaphores for syncronization, I will also need to pass the shared semaphore's mmap. There is a code snippet below from the caller's main to execute slaves. I can reach newArgv by using argv in the slaves' main:

int f = open(argv[1], O_RDWR);

unsigned int *addr = mmap(0, 10000, PROT_READ | PROT_WRITE, MAP_SHARED, f, 0);

char * newArgv[10];
for (int a = 0; a < numberOfFiles; a++) {
    newArgv[0] = wordToSearch;
    newArgv[1] = argv[3 + a];
    char * path = "./psearch2aslave";
    execve(path, newArgv, NULL);
}

You cannot pass mmap to an execve -ed executable.

When execve is successful, the entire virtual address space is scraped and reinitialized for the executed ELF binary. That is one of the main roles of execve(2) . At startup, a program should expect a well defined memory state.

Maybe you might adopt a convention , like using some named file, and pass the name of that file as some program argument. Or passing a file descriptor, etc.

(IIRC, someone proposed many years ago a kernel patch to add a flag to mmap(2) for memory mappings persistent accross execve ; that patch was rejected, with good reasons; I completely forgot the details and could be very wrong)

Perhaps you want shm_overview(7) . Or just adopt a convention with some file name and use mmap with MAP_SHARED .

Be aware that even if you share (virtual) memory, you need some means of synchronization. Read sem_overview(7) , futex(7) , ....

Read also ALP and Operating Systems: Three Easy Pieces (both freely downloadable). See also syscalls(2) (there are several ways to do inter-process communication ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM