C program to execute multiple Unix commands in parallel
Lab 6 – exec()
Part I
Write a C program called executebash.c. It prints out on the screen
EXAM! EXAM! EXAM!
and then forks a child to execute a bash script named mybash. This mybash program prints out on
the screen
STUDY! STUDY! STUDY!
Part II
Write a C program to execute multiple Unix commands in parallel.
• The number of Unix commands is not fixed.
• There is no communication among the Unix commands.
• The Unix commands are given as command line arguments.
• For simplicity, you can assume that each Unix command has exactly one argument
except that the last one can have either no argument or one argument.
For example,
>>>>> miniminishell cat openfile.c ls –l ps
includes three Unix commands: cat with one argument openfile.c, ls with one argument –l, and
ps with no argument.
For each Unix command, use a separate process to execute it. You need to print out each process
id.
Answer:
PART 1
executebash.c
#include<unistd.h> #include<stdio.h> #include<sys/wait.h> int main(){ int n; printf("EXAM EXAM EXAM!\n"); if(fork() == 0){ execlp("./mybash.sh","mybash.sh", "echo", (char*)NULL); } else{ wait(&n); } }
mybash
#!/bin/bash echo "STUDY! STUDY! STUDY!"
PART 2
openfile.c
#include<unistd.h> #include<stdio.h> int main(){ printf("EXAM EXAM EXAM!\n"); if(fork() == 0){ execlp("./mybash.sh","mybash.sh", "echo", (char*)NULL); } }
miniminishell.c
#include<unistd.h> #include<stdio.h> #include<sys/wait.h> int main(int argc, char *argv[]){ int n; int pid; for(int i=1;i<argc;i+=2){ pid=fork(); if(pid == 0){ if(argc > 1){ printf("Process ID = %d\n", getpid()); execlp(argv[i],argv[i],argv[i+1], (char*)NULL); } } else if(pid>0){ wait(&n); } else{ printf("exex failed "); } } return 0; }
Leave a reply