Implementation of Data Communication Between processes in Visual C ++

Source: Internet
Author: User
Implementation of Data Communication Between processes visual C ++ http://tech.163.com 12:18:21 Source: Tianji development comments 0 Forum

In Windows, data is often exchanged and transmitted between applications (processes), which solves the problem of data communication between processes. In the original 16-bit Windows 3.x system, all Windows applications share a single address, and any process can read and write the data in this shared address space. With the emergence of 32-bit operating systems such as windwos98, WindowsNT, and Windows2000, each process must have its own address space. A Windows process cannot access the private data of another process, that is, although two processes can use pointers with the same value to address each other, all they read and write is their own data, which reduces mutual interference between processes. So does the adoption of the above technology mean that data exchange cannot be performed between various applications? The answer is no. The powerful windows system has already designed many solutions for us to solve communication problems. Here we only discuss how to use Dynamic Data Exchange (DDE) method to implement data communication between processes.

The functions of this instance program are as follows. The server has two data items, one being the input string and the other being the regularly added integer. After running the two instances of the program, the two programs can establish a DDE connection to transfer data and display the data transmitted by the other instance. After compiling and running the program:


Figure 1 interface for implementing the data communication program between processes using the DDE Method

   I. Implementation Method

Since Microsoft launched the Windows operating system, Dynamic Data Exchange (DDE) has become part of windows, and many windwos applications use the DDE technology to exchange data between processes. DDE is a protocol based on the Windows internal message system, global and shared global memory. It is used to coordinate data exchange and command calls between Windows applications, it has become a common method for communication between applications.

DDE applications can be divided into four types: customer type, server type, customer/server type, and monitor. The DDE session occurs between the client application and the server application. The customer application requests data or services from the server application, and the server application responds to the data or service requests of the customer application. A client/server application can send requests and provide information, while a monitor application is intended for language debugging.

The DDE protocol uses a three-level tree name: Service, topic, and item to identify the data unit to be transmitted by DDE. The service enables the application to exchange data to other programs. The topic is similar to a directory and is a parameter for establishing a session connection. item is the data content to be transmitted during DDE communication, for example, a data or a string.

The dynamic exchange management library (ddeml) provides DDE and application-level protocols. Applications developed using ddeml have better performance than those without ddeml in terms of running consistency and communication between applications. In addition, ddeml applications make it much easier to develop applications that support DDE.

After a DDE session is established, the customer program and the server program can exchange data through three links: 1. Cold link: Customer Program Application Data, the server program immediately sends data to the customer program. 2. Warm link: the server program notifies the customer program that the data item has changed, but does not send the value that has occurred to the customer program. 3. Hot Link: when a data item changes, the server program immediately sends the changed value to the customer program. This is the most common and convenient method, this method is used in the following example.

DDE Session Initialization

Use the API function ddeinitialize () to register an application in ddeml.

Session Creation

Server: register the ddenameservice service.

Customer: connect to ddeconnect.

Session Process

Similar to Windows message loop, the session process is the process of transaction processing. The customer uses ddeclienttransaction () to send transaction requests. Through the DDE callback function, the server processes client transaction requests and returns ddecreatedatahandle to send data. At the same time, the customer can call ddegetdata () to obtain data.

Session ends

The service provider or the customer can terminate the session. When a program is launched, the service should be cleared, resources should be released, and ddeuninitialize () should be called ().

   Ii. programming steps

1. Start visual c ++ 6.0 and create a dialog box-based MFC application named ddedemo, add two group box controls and place the edit controls idc_edit, static controls id_static1, id_static2, and id_static3 on them, and use Wizard to add corresponding members to change m_edit (cstring type ), add and leave the caption empty, as shown in interface 1;

2. Use classwizard to add the dialog box functions, which are the en_change messages of wm_destory, wm_initdialog, wm_timer, and idc_edit respectively;

3. Add # include "ddel. H" to ddemodlg. cpp to use the ddeml function. Add the following macro definitions and global variables:

# Define nitem 2 // defines the number of items;
Const char szapp [] = "server"; // server DDE Service name;
Const char sztopic [] = "topic"; // server DDE directory name;
Const char * pszitem [nitem] = {"Item1", "item2"}; // server item name string array;
Int COUNT = 0; // count, which is displayed in static1;
Cstring serverdata [nitem]; // stores data items on the server;
Hconv = 0; // session handle;
DWORD idlnst = 0; // ddeml instance handle;
Hwnd; // window handle;
Handle hlnst; // instance handle;
Hsz hszapp = 0; // server service string handle;
Hsz hsztopic = 0; // server directory string handle;
Hsz hszitem [nitem]; // server item string handle;
Bool bconnect; // The connection flag;

4. Enter the code and compile and run the program.

3. program code

/// // DDE callback function;
Hddedata callback ddecallback (uint wtype, uint wfmt, hconv, hsz topic, hsz item,
Hddedata hdata, DWORD ldata1, DWORD ldata2)
{
Int I;
Char TMP [255];
Switch (wtype)
{
Case xtyp_advstart:
Case xtyp_connect: // request connection;
Return (hddedata) True); // allow;
Case xtyp_advdata: // data arrival;
For (I = 0; I if (item = hszitem [I])
{
Ddegetdata (hdata, (pbyte) TMP, 255, 0); // get data;
Switch (I)
{
Case 0:
Setdlgitemtext (hwnd, idc_static2, TMP );
Break;
Case 1:
Setdlgitemtext (hwnd, idc_static3, TMP );
Break;
}
}
Return (hddedata) dde_fack); // receipt;
Case xtyp_advreq:
Case xtyp_request: // data request;
For (I = 0; I if (item = hszitem [I])
Return (ddecreatedatahandle (idlnst, (pbyte) (lpctstr) serverdata [I],
Serverdata [I]. getlength () + 1, 0, item, wfmt, 0 ));
}
Return (0 );
}

///////////////////////////////////////////////////// CddedemoDlg.cpp
CDdedemoDlg::CDdedemoDlg(CWnd* pParent /*=NULL*/)
: CDialog(CDdedemoDlg::IDD, pParent)
{
 //{{AFX_DATA_INIT(CDdedemoDlg)
  m_edit = _T("");
 //}}AFX_DATA_INIT
 // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
 m_hIcon = AfxGetApp()-> LoadIcon(IDR_MAINFRAME);
}
void CDdedemoDlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{{AFX_DATA_MAP(CDdedemoDlg)
  DDX_Text(pDX, IDC_EDIT1, m_edit);
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDdedemoDlg, CDialog)
//{{AFX_MSG_MAP(CDdedemoDlg)
 ON_WM_SYSCOMMAND()
 ON_WM_PAINT()
 ON_WM_QUERYDRAGICON()
 ON_WM_TIMER()
 ON_WM_DESTROY()
 ON_EN_CHANGE(IDC_EDIT1, OnChangeEdit1)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

//////////////////////////////////////////CDdedemoDlg message handlers
BOOL CDdedemoDlg::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
Hwnd = m_hwnd;
If (ddeinitialize (& idlnst, (pfncallback) ddecallback, appcmd_filterinits |
Cbf_fail_executes | cbf_skip_connect_confirms | cbf_fail_selfconnections |
Cbf_fail_pokes, 0 ))
{
MessageBox ("DDE Server initialization failed! ");
Return false;
}
Hlnst = afxgetapp ()-> m_hinstance;
// Create a DDE string
Hszapp = ddecreatestringhandle (idlnst, szapp, 0 );
Hsztopic = ddecreatestringhandle (idlnst, sztopic, 0 );
For (INT I = 0; I hszitem [I] = ddecreatestringhandle (idlnst, pszitem [I], 0 );
// Register the service;
Ddenameservice (idlnst, hszapp, 0, dns_register );
Bconnect = false;
Settimer (, null); // start timing;
Return true; // return true unless you set the focus to a control
}

void CDdedemoDlg::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 CDdedemoDlg::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 CDdedemoDlg::OnQueryDragIcon()
{
 return (HCURSOR) m_hIcon;
}

Void cddedemodlg: ontimer (uint nidevent)
{
// Todo: add your message handler code here and/or call default
Count ++;
Serverdata [1]. Format ("% d", count );
Setdlgitemtext (idc_static1, serverdata [1]);
Ddepostadvise (idlnst, hsztopic, hszitem [1]); // notifies you of updates;
If (! Bconnect) // if no connection is established
{
Hconv = ddeconnect (idlnst, hszapp, hsztopic, null );
// Connect to the server;
If (hconv) // if the creation is successful
{
DWORD dwresult;
Bconnect = true;
For (INT I = 0; I ddeclienttransaction (null, 0, hconv, hszitem [I], cf_text, xtyp_advstart,
Timeout_async, & dwresult );
}
}
Cdialog: ontimer (nidevent );
}

Void cddedemodlg: ondestroy ()
{
Cdialog: ondestroy ();
// Todo: add your message handler code here
Killtimer (1); // destruction timing;
Ddenameservice (idlnst, dns_unregister); // deregister the service;
Ddefreestringhandle (idlnst, hszapp );
Ddefreestringhandle (idlnst, hsztopic );
For (INT I = 0; I ddefreestringhandle (idlnst, hszitem [I]);
Ddeuninitialize (idlnst );
}

Void cddedemodlg: onchangeedit1 ()
{
// Todo: if this is a RichEdit control, the control will not
// Send this notification unless you override the cdialog: oninitdialog ()
// Function and call cricheditctrl (). seteventmask ()
// With the enm_change flag ored into the mask.
// Todo: add your control notification handler code here
Updatedata ();
Serverdata [0] = m_edit;
Ddepostadvise (idlnst, hsztopic, hszitem [0]); // notify DDE to update the data item;
}

   Iv. Summary

Windows provides many methods to implement communication between processes and transmit data to each other, such as the system clipboard method, shared DLL method, and pipeline method, the existence of these methods ensures the robustness and robustness (stability) of the program. Interested readers can refer to the relevant materials on their own.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.