Pipes Dynamically
Pipes Dynamically
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[MAX_MESSAGE_SIZE];
// Create a pipe
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
perror("fgets");
exit(EXIT_FAILURE);
}
// Remove the trailing newline character from fgets input
buffer[strcspn(buffer, "\n")] = 0;
pid = fork();
if (pid == -1) {
// If fork fails
perror("fork");
exit(EXIT_FAILURE);
if (pid == 0) {
close(pipefd[0]);
} else {
close(pipefd[1]);
}
return 0;
Fifo
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
pid_t pid;
char buffer[MAX_MESSAGE_SIZE];
int fifo_fd;
exit(EXIT_FAILURE);
perror("fgets");
exit(EXIT_FAILURE);
buffer[strcspn(buffer, "\n")] = 0;
pid = fork();
if (pid == -1) {
// If fork fails
perror("fork");
exit(EXIT_FAILURE);
if (pid == 0) {
if (fifo_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
} else {
if (fifo_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
unlink(FIFO_NAME);
return 0;
Shared memory:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
int main() {
pid_t pid;
int shm_id;
char *shm_ptr;
char input_str[SHM_SIZE];
if (shm_id == -1) {
perror("shmget failed");
exit(EXIT_FAILURE);
}
// Attach the shared memory segment to the address space of the process
perror("shmat failed");
exit(EXIT_FAILURE);
pid = fork();
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
if (pid == 0) {
if (shmdt(shm_ptr) == -1) {
exit(EXIT_FAILURE);
} else {
strcpy(shm_ptr, input_str);
wait(NULL);
if (shmdt(shm_ptr) == -1) {
exit(EXIT_FAILURE);
perror("shmctl failed");
exit(EXIT_FAILURE);
return 0;
Message queue
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
// Message structure
struct msg_buffer {
int main() {
pid_t pid;
int msgid;
if (msgid == -1) {
perror("msgget failed");
exit(EXIT_FAILURE);
pid = fork();
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
if (pid == 0) {
perror("msgrcv failed");
exit(EXIT_FAILURE);
} else {
perror("msgsnd failed");
exit(EXIT_FAILURE);
wait(NULL);
}
return 0;