Program description:

Lab 5

  1. Carefully study the examples provided: fork.c, myls.c, myshell.c, etc. You need to know how they work in order for you to finish this assignment; the examples will also get you prepared for assignment 3.
  2. Write a program called minishell that creates two child processes: one to execute 'ls' and the other to execute 'sort'. After the forks, the original parent process waits for both child processes to finish before it terminates. The standard output of 'ls' process should be piped to the input to the 'sort' process. Make sure you close the unnecessary open files for the three processes.
    Please follow the following instructions carefully before submitting your work:
  • Submit this assignment as FirstnameLastnameL5.zip. Submit a zip file containing your source code and Makefile.
  • You need to create a Makefile to build your source code into an executable. The Makefile should also include a target 'clean' to clean up miscellaneous files (*.o, the executable file, *~, core, etc.).
    Before submission, make sure you clean up the directories so that no miscellaneous files are kept around in the submission.
Your code:

Make file

minishell: minishell.c
	gcc -o minishell minishell.c -I.
clean:
	rm -f minishell *.o *.err core *~

.c File

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>


char *cmd1[] = { "ls", 0 };
char *cmd2[] = { "sort", 0 };

void runsource(int pfd[]);
void rundest(int pfd[]);

int
main(int argc, char **argv)

{   //initialization
	int pid, status;
	int fd[2];

	pipe(fd);

	runsource(fd);
	rundest(fd);
	close(fd[0]); close(fd[1]); 	// close both file descriptors on the pipe 

	while ((pid = wait(&status)) != -1) {}	// pick up all the finished children
		
	exit(0);
}


void runsource(int pfd[])	// run the first part of the pipeline (cmd1) 
{
	int pid;	/* we don't use the process ID here, but you may wnat to print it for debugging */

	switch (pid = fork()) {

	case 0: // child 
		dup2(pfd[1], 1);	// this end of the pipe becomes the standard output
		close(pfd[0]); 		// close the other end of the pipe
		execvp(cmd1[0], cmd1);	// run the command
		perror(cmd1[0]);	// run this if it failed

	default: // parent does nothing 
		break;

	case -1:
		perror("fork");
		exit(1);
	}
}

void rundest(int pfd[])	// run the second part of the pipeline (cmd2)
{
	int pid;

	switch (pid = fork()) {

	case 0: // child 
		dup2(pfd[0], 0);	// this end of the pipe becomes the standard input 
		close(pfd[1]);		// close the other end of the pipe 
		execvp(cmd2[0], cmd2);	// run the command 
		perror(cmd2[0]);	// run this if it failed

	default: // parent does nothing 
		break;

	case -1:
		perror("fork");
		exit(1);
	}
}

All the assignments will be posted. Subscribe for more! :)