IPC_Mechanisms_Windows
IPC_Mechanisms_Windows
ANAND
MRITS_CSE
Lab _OS
a) Unnamed Pipes
• Aim: To demonstrate IPC using unnamed pipes between parent and child processes in
Windows.
• Algorithm:
parent_pipe.c
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hRead, hWrite;
SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
PROCESS_INFORMATION pi;
STARTUPINFO si = {sizeof(STARTUPINFO)};
char buffer[] = "Hello from Parent Process";
char commandLine[] = "child_pipe.exe";
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = hRead;
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
DWORD written;
WriteFile(hWrite, buffer, sizeof(buffer), &written, NULL);
CloseHandle(hWrite);
CloseHandle(hRead);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}
child_pipe.c
#include <windows.h>
#include <stdio.h>
int main() {
char buffer[100];
DWORD bytesRead;
Output:
fifo_server.c
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hPipe;
char buffer[1024];
DWORD bytesRead;
hPipe = CreateNamedPipe(TEXT("\\.\pipe\MyNamedPipe"),
PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_WAIT,
1, 1024, 1024, 0, NULL);
fifo_client.c
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hPipe;
DWORD bytesWritten;
Output:
shm_writer.c
#include <windows.h>
#include <stdio.h>
#include <string.h>
int main() {
HANDLE hMapFile;
LPCTSTR pBuf;
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
A.ANAND
MRITS_CSE
shm_reader.c
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hMapFile;
LPCTSTR pBuf;
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
Output:
1Sender creates or opens a file and writes messages to it (simulate message send).
2Receiver opens the same file and reads messages (simulate message receive).
3Synchronization or queue logic can be handled via file locks or using higher-level APIs like
PostMessage between GUI apps.
sender.c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr = fopen("msgqueue.txt", "w");
if (fptr == NULL) {
printf("Unable to open file.\n");
return 1;
}
fprintf(fptr, "Hello from sender process!\n");
fclose(fptr);
printf("Message sent.\n");
return 0;
}
receiver.c
#include <stdio.h>
#include <stdlib.h>
int main() {
char buffer[256];
FILE *fptr = fopen("msgqueue.txt", "r");
if (fptr == NULL) {
printf("Unable to open file.\n");
A.ANAND
MRITS_CSE
return 1;
}
fgets(buffer, sizeof(buffer), fptr);
printf("Message received: %s", buffer);
fclose(fptr);
return 0;
}