Lab7 BSSE6A
Lab7 BSSE6A
Lab7 BSSE6A
Lab Task 7
Task 1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define READ_END 0
#define WRITE_END 1
int main() {
int pipe_fd[2];
pid_t pid;
if (pipe(pipe_fd) == -1) {
perror("pipe creation failed");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
return 0;
}
Task 2
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define READ_END 0
#define WRITE_END 1
int main() {
int pipe_fd[2];
pid_t pid;
char message[] = "Hello, dear child! This message is from the parent process.";
if (pipe(pipe_fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid > 0) {
// This is the parent process
close(pipe_fd[READ_END]); // Close the unused read end
write(pipe_fd[WRITE_END], message, strlen(message) + 1);
close(pipe_fd[WRITE_END]);
} else {
// This is the child process
close(pipe_fd[WRITE_END]); // Close the unused write end
char received_message[100];
read(pipe_fd[READ_END], received_message, sizeof(received_message));
printf("Child process received this message: %s\n", received_message);
close(pipe_fd[READ_END]);
}
return 0;
}