/* wmutex-parent.c */
#include <stdio.h>
#include <string.h>
#include <windows.h>
int main(int argc, char **argv)
{
int i;
HANDLE *procs, *threads;
const char *program = "wmutex-child.exe";
int count = 4;
DWORD word;
/* Create shared memory area and give it a unique name */
HANDLE shmem = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, sizeof(unsigned), "share_data");
/* Get a view of the file (can be all or just a part) */
unsigned *value = (unsigned *)MapViewOfFile(shmem, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(unsigned));
/* Create a mutex to share with the other processes */
HANDLE mutex = CreateMutex(NULL, FALSE, "share_mutex");
/* The user can specify the number of processes */
if (argc > 1)
count = atoi(argv[1]);
procs = (HANDLE *)malloc(count * sizeof(HANDLE));
threads = (HANDLE *)malloc(count * sizeof(HANDLE));
*value = 0; /* initialize shared memory */
for (i = 0; i < count; i++)
{
int result;
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
result = CreateProcess (program, 0, 0, 0, TRUE, 0, 0, 0, &si, &pi);
procs[i] = pi.hProcess;
threads[i] = pi.hThread;
}
/* Wait for all processes to finish */
WaitForMultipleObjects(count, procs, TRUE, INFINITE);
printf("Value is %u\n", *value);
/* Cleanup everything */
for (i = 0; i < count; i++)
{
CloseHandle(procs[i]);
CloseHandle(threads[i]);
}
UnmapViewOfFile(value);
CloseHandle(shmem);
CloseHandle(mutex);
free(procs);
free(threads);
return 0;
}