Click here to Skip to main content
15,885,182 members
Articles / Desktop Programming / MFC

Shared Memory with IPC with threads

Rate me:
Please Sign up or sign in to vote.
3.32/5 (18 votes)
4 Oct 2004CPOL2 min read 125.7K   4.2K   45  
Shared memory as used along with threads to communicate between processes.
// OneAtaTimeDlg.cpp : implementation file
//

#include "stdafx.h"
#include "OneAtaTime.h"
#include "OneAtaTimeDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
HANDLE kSendCommand;
HANDLE kReceiveCommand;

HANDLE kSendMessage;
HANDLE kReceiveMessage;

HANDLE kChildAck; // Acknowledgement By The Child

CWinThread* thread;

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// COneAtaTimeDlg dialog

COneAtaTimeDlg::COneAtaTimeDlg(CWnd* pParent /*=NULL*/)
	: CDialog(COneAtaTimeDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(COneAtaTimeDlg)
	m_status = _T("");
	m_message = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void COneAtaTimeDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(COneAtaTimeDlg)
	DDX_Control(pDX, IDC_LIST_RECVMESSAGE, m_recvlist);
	DDX_Text(pDX, IDC_STATIC_STATUS, m_status);
	DDX_Text(pDX, IDC_EDIT_MESSAGE, m_message);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(COneAtaTimeDlg, CDialog)
ON_MESSAGE(KILL_APP,OnKillApp)
ON_MESSAGE(RECV_MESSAGE,OnRecvMessage)
ON_MESSAGE(CHILD_START,OnChildStart)
	//{{AFX_MSG_MAP(COneAtaTimeDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CREATE()
	ON_BN_CLICKED(IDC_BUTTON_KILL, OnButtonKill)
	ON_BN_CLICKED(IDC_BUTTON_SEND, OnButtonSend)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// COneAtaTimeDlg message handlers

BOOL COneAtaTimeDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	if(kParentOrChild) // This is the parent. Receive the message from child.
	{
		this->SetWindowText("Parent: Receiving Command");
		GetDlgItem(IDC_BUTTON_KILL)->DestroyWindow();
		GetDlgItem(IDC_EDIT_MESSAGE)->EnableWindow(false);
		GetDlgItem(IDC_BUTTON_SEND)->EnableWindow(false);
		thread = AfxBeginThread(StartProbing,GetSafeHwnd(),THREAD_PRIORITY_NORMAL); // Start Checking for Commands from Child
		if(thread != NULL)
		{
			UpdateData(true);
			m_status = "Parent waiting for messages ...";
			UpdateData(false);

		}
		else
		{
			UpdateData(true);
			m_status = "Thread not started ...";
			UpdateData(false);

		}
		

	}
	else
	{
		GetDlgItem(IDC_BUTTON_KILL)->EnableWindow(true);
		kShMem->childAck = TRUE;
		::SetEvent(kChildAck);
		this->SetWindowText("Child: Send Command / Message to Parent");

	}

	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void COneAtaTimeDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void COneAtaTimeDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR COneAtaTimeDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

int COneAtaTimeDlg::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	CString title;
//	UpdateData(true);
	if (CDialog::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	
	kProcessId = ::GetCurrentProcessId();
	title.Format("Process: %d",kProcessId);
	this->SetWindowText(title);
	
	/* Create a file map for sharing the memory. This is for sharing the memory between same processes. */
	kMap = CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE,0,sizeof(KSharedMemory),"KBuildDevelop");
	if(GetLastError() == ERROR_ALREADY_EXISTS)
	{
		// COMMENTED SECTION BELOW [TEST]: This was great. Identifies if the process has been created earlier or not. 
		/*MessageBox("One at a time please !!","One At A Time", MB_OK);
		::PostQuitMessage(0);*/
		kMap = ::OpenFileMapping(FILE_MAP_WRITE,FALSE,"KBuildDevelop");
		kMutex = ::CreateMutex(NULL,FALSE,"KBuildDevelop");
		kParentOrChild = FALSE;
		
	}
	else
	{
		kParentOrChild = TRUE;
	}

	kShMem = (KSharedMemory*)::MapViewOfFile(kMap,FILE_MAP_WRITE,0,0,sizeof(KSharedMemory));

	kSendCommand = ::CreateEvent(NULL,FALSE,FALSE,"SendCommand");
	kSendMessage = ::CreateEvent(NULL,FALSE,FALSE,"SendMessage");
	kReceiveMessage = ::CreateEvent(NULL,FALSE,FALSE,"ReceiveMessage");
	kReceiveCommand = ::CreateEvent(NULL,FALSE,FALSE,"ReceiveCommand");
	kChildAck = ::CreateEvent(NULL,FALSE,FALSE,"ChildAcknowledge");




	return 0;
}


UINT StartProbing(LPVOID lParam)
{
	while(1)
	{
		if(::WaitForSingleObject(kChildAck,10)== WAIT_OBJECT_0) /* Wait for acknowledgement from the child */
			PostMessage((HWND) lParam,CHILD_START,0,0);
		if(::WaitForSingleObject(kSendCommand, 10) == WAIT_OBJECT_0)
		{
			PostMessage((HWND) lParam, KILL_APP,0,0);
			::SetEvent(kReceiveCommand);
			break;

		}	
		else
		{
			// Add code here to wait for another event. 
			if(::WaitForSingleObject(kSendMessage, 10) == WAIT_OBJECT_0)
			{
				PostMessage((HWND) lParam, RECV_MESSAGE,0,0);
				::SetEvent(kReceiveMessage);
			}
		}
	
	}
	return 0;

}


void COneAtaTimeDlg::OnKillApp()
{
	
		PostQuitMessage(0);

}

void COneAtaTimeDlg::OnButtonKill() 
{

		::SetEvent(kSendCommand);
		::ReleaseMutex(kMutex);

}

void COneAtaTimeDlg::OnButtonSend() 
{
	UpdateData(true);
	char buffer[100];
	sprintf(buffer,"%s",m_message);
	strcpy(kShMem->data,buffer);
	m_message=_T("");
	UpdateData(false);
	::SetEvent(kSendMessage);// Set send message event

}

void COneAtaTimeDlg::OnRecvMessage()
{
	UpdateData(true);
	if(strcmp(kShMem->data,"bye")==0)
		PostQuitMessage(0);
	m_recvlist.AddString(kShMem->data);
	UpdateData(false);


}

void COneAtaTimeDlg::OnChildStart()
{
	UpdateData(true);
	m_status = "Child Started...";
	UpdateData(false);

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
I am a personality from Trivandrum , a green peaceful place in Kerala, South India.
I have been an enthusiast of Windows programming when I started creating simple windows when I learnt VC++ in LCC in Trivandrum. From then on its all about Windows in my flesh and blood.
My career graph moves like this:
1. I started working as a C/C++ programmer in a company in Trivandrum where I learnt the ABCs of Software Industry. I worked with them for about 1 year. I could not contine since I was in contract for 1 year.
2. Then I joined another organization in Trivandrum who gave me challenges to love. They made me mad about VC++ and Windows.
I was mad about Embedded Systems which made me, Myself = Embedded Systems + VC++.
3. Software Engineer in a telecom company in Hyderabad, Andhra Pradesh, S.India.
4. Currently working with a telecom company in Bangalore.
I totally, so, have experience of about 4.5 years.

Comments and Discussions