Description
C Program with two processes
Demonstrate each of the following steps to the TA to get a grade on this part of the lab assignment
- Please write the following C program in a Linux environment using vi, emacs, or an editor of your choice
/*Sample C program for Lab assignment 1*/
#include <stdio.h> /* printf, stderr */
#include <sys/types.h> /* pid_t */
#include <unistd.h> /* fork */
#include <stdlib.h> /* atoi */
#include <errno.h> /* errno */
/* main function with command-line arguments to pass */
int main(int argc, char *argv[]) {
pid_t pid;
int i, n = atoi(argv[1]); // n microseconds to input from keyboard for delay
printf(“\n Before forking.\n”);
pid = fork();
if (pid == -1) {
fprintf(stderr, “can’t fork, error %d\n”, errno);
}
if (pid){
// Parent process
for (i=0;i<100;i++) {
printf(“\t \t \t Parent Process %d \n”,i);
usleep(n);
}
}
else{
// Child process
for (i=0;i<100;i++) {
printf(“Child process %d\n”,i);
usleep(n);
}
}
return 0;
}
- Compile the program using gcc compiler by typing gcc YourProgram.c – o ExecutableName. When it compiles without errors or warnings, make a copy of the source file then go to step 3.
- Run the program by typing ./ExecutableName and take a note of your observation.
- Re-run the program by typing ./ExecutableName Note that the delay in the loop depends on the command line argument you give, here the delay is 3000 microseconds.
- Enter delays of 500 and 5000, what happens?
- Take-Home Programming Task (attempt this on your own and be prepared to demo your solution):
Write a program that will result in the creation of exactly seven processes (including the initial program itself – parent). Do not allow any single process to create any more, or any less, than two child processes. Processes may have two children, or no children at all.
C Program with two threads
- Rewrite the program in Step 1. with two threads instead of two processes, then demonstrate steps 1 – 3
Changing the context of the process
Processes are often created to run separate programs. In this case, a process context is changed by causing it to replace its execution image by with an execution image of a new program, exec( ) system call is used. Although the process loses its code space, data space, stack, and heap, it retains its process ID, parent, child processes, and open file descriptors. Six versions of exec( ) exist. The simplest and widely used:
- execlp(char *filename, char *arg0, char arg1,….. , char *argn, (char *) 0);
- g. execlp( “sort”, “sort”, “-n”, “foo”, 0); à $ sort -n, foo
- Rewrite the program in Step 1., so that the child process runs the ls command, and that the parent parent process waits until the child process terminates before it exits. Demonstrate your code to the TA. You may use the following code snippet.
else if(pid == 0)
{
execlp(“/bin/ls”, “ls”, NULL);
}
else
{
wait(NULL);
printf(“Child Complete”);
exit(0);
}



