OS Lab Ass 2 (21-SE-84)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

OS Lab Assignment 2

Subject: Operating System Lab

Submitted To: Mam Saba Awan

Submitted By: Muhammad Usman

Registration No: 21-SE-84

Section: Omega

Software Engineering Department


University Of Engineering and Technology, Taxila
LAB Assignment:
Write a program in which parent writes and executes a command and Child reads and
executes another command. This program is the equivalent of running the shell command:

C CODE:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// Close the write end of the pipe since the child will only read
close(pipefd[1]);
// Redirect stdin to read from the pipe
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[0]);
char *cmd2[] = { "/usr/bin/tr", "a-z", "A-Z", NULL };
execvp(cmd2[0], cmd2);
perror("execvp");
exit(EXIT_FAILURE);
} else {
// Close the read end of the pipe since the parent will only write
close(pipefd[0]);
// Redirect stdout to write to the pipe
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
char *cmd1[] = { "/bin/ls", "-al", "/", NULL };
execvp(cmd1[0], cmd1);
// If execvp fails
perror("execvp");
exit(EXIT_FAILURE);
}
wait(NULL);
return 0;
}
Output:

You might also like