IPC Programs in C
1. Pipes - Parent to Child Communication
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd[2];
char message[] = "Hello child!";
char buffer[100];
if (pipe(fd) == -1) {
perror("Pipe failed");
exit(1);
}
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(1);
}
if (pid > 0) {
close(fd[0]);
write(fd[1], message, strlen(message) + 1);
printf("Parent sent: %s\n", message);
close(fd[1]);
} else {
close(fd[1]);
read(fd[0], buffer, sizeof(buffer));
printf("Child received: %s\n", buffer);
close(fd[0]);
}
return 0;
}
2. Shared Memory - Writer
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
int main() {
key_t key = ftok("progfile", 65);
int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
char *str = (char*) shmat(shmid, NULL, 0);
strcpy(str, "Hello from Shared Memory Writer!");
printf("Data written: %s\n", str);
shmdt(str);
return 0;
}
3. Shared Memory - Reader
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main() {
key_t key = ftok("progfile", 65);
int shmid = shmget(key, 1024, 0666);
char *str = (char*) shmat(shmid, NULL, 0);
printf("Data read: %s\n", str);
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
4. Message Queue - Sender
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct message {
long msg_type;
char msg_text[100];
};
int main() {
key_t key = ftok("progfile", 65);
int msgid = msgget(key, 0666 | IPC_CREAT);
struct message msg;
msg.msg_type = 1;
strcpy(msg.msg_text, "Hello from sender!");
msgsnd(msgid, &msg, sizeof(msg.msg_text), 0);
printf("Message sent: %s\n", msg.msg_text);
return 0;
}
5. Message Queue - Receiver
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct message {
long msg_type;
char msg_text[100];
};
int main() {
key_t key = ftok("progfile", 65);
int msgid = msgget(key, 0666 | IPC_CREAT);
struct message msg;
msgrcv(msgid, &msg, sizeof(msg.msg_text), 1, 0);
printf("Message received: %s\n", msg.msg_text);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}