Practical 07
Title : Inter-process Communication (IPC) in Linux
=======================================================================
Inter-process Communication (IPC) in Linux is crucial for allowing processes to communicate with each other.
1. Pipes : Simple Parent-Child Communication
pipe_example.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd[2];
pid_t pid;
char write_msg[] = "Hello, world!";
char read_msg[20];
if (pipe(fd) == -1) {
perror("pipe");
return 1;
}
pid = fork();
if (pid < 0) {
perror("fork");
return 1;
} else if (pid == 0) { // Child process
close(fd[0]); // Close unused read end
write(fd[1], write_msg, strlen(write_msg) + 1);
close(fd[1]); // Close write end
} else { // Parent process
close(fd[1]); // Close unused write end
read(fd[0], read_msg, sizeof(read_msg));
printf("Parent read: %s\n", read_msg);
close(fd[0]); // Close read end
}
return 0;
}
`
Compilation and Execution:
$gcc -o pipe_example pipe_example.c
$./pipe_example
Expected Output:
Parent read: Hello, world!
2. Message Queues : Sending and Receiving Messages
msg_queue_example.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
struct msg_buffer {
long msg_type;
char msg_text[100];
} message;
int main() {
key_t key;
int msgid;
key = ftok("progfile", 65);
msgid = msgget(key, 0666 | IPC_CREAT);
message.msg_type = 1;
strcpy(message.msg_text, "Hello, world!");
msgsnd(msgid, &message, sizeof(message), 0);
printf("Sent message: %s\n", message.msg_text);
msgrcv(msgid, &message, sizeof(message), 1, 0);
printf("Received message: %s\n", message.msg_text);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
Compilation and Execution:
$gcc -o msg_queue_example msg_queue_example.c
$./msg_queue_example
Expected Output:
Sent message: Hello, world!
Received message: Hello, world!
3. Shared Memory : Writing and Reading Shared Memory
shm_example.c
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
int main() {
key_t key = ftok("shmfile", 65);
int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
char *str = (char*) shmat(shmid, (void*)0, 0);
strcpy(str, "Hello, world!");
printf("Data written in memory: %s\n", str);
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
Compilation and Execution:
$gcc -o shm_example shm_example.c
$./shm_example
Expected Output:
Data written in memory: Hello, world!
`
Conclusion: practical implementations of various IPC mechanisms in Linux. You can build more complex applications by combining these techniques as needed.
No comments:
Post a Comment