In: Computer Science
2. Run the following C program, and submit the screenshot of the
result. Also briefly explain the result.
#include <sys/types.h> #include <stdio.h> #include
<unistd.h>
#define SIZE 5
int nums[SIZE] = {0,1,2,3,4};
int main() { int i; pid_t pid; pid = fork();
if (pid == 0) { for (i = 0; i < SIZE; i++) { nums[i] *= -i;
printf("CHILD: %d ",nums[i]); /* LINE X */ } } else if (pid > 0)
{ wait(NULL);
for (i = 0; i < SIZE; i++) printf("PARENT: %d ",nums[i]); /*
LINE Y */
}
return 0;
}
3. Run the following program and take a screenshot of the result.
Explain the relationship between the created processes. (Hint: if
we draw an arrow that points from a process to its child process,
what shape can we get?)
#include <sys/types.h> #include <stdio.h> #include
<unistd.h>
int main (int argc, char *argv[]) { pid_t childpid = 0; int i,
nbrOfProcesses; if (argc != 2) { /* Check for valid number of
command-line arguments */ fprintf(stderr, "Usage: %s
<processes>\n", argv[0]); return 1; }
/* Convert character string to integer */ nbrOfProcesses =
atoi(argv[1]); for (i = 1; i < nbrOfProcesses; i++) { childpid =
fork(); if (childpid == -1) { printf("Fork failed"); exit(1); }
else if (childpid != 0) // True for a parent break; } // End
for
// Each parent prints this line fprintf(stderr, "i: %d process ID:
%4ld parent ID: %4ld child ID: %4ld\n", i, (long)getpid(),
(long)getppid(), (long)childpid);
sleep(5); // Sleep five seconds
return 0;
} // End main
Code:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define SIZE 5
int nums[SIZE] = {0, 1, 2, 3, 4};
int main() {
int i;
pid_t pid;
//fork() is used to create a new child process
pid = fork();
// if(pid == 0) tells if the current process is child process
// LINE X is a part of the child process
if (pid == 0)
{
for (i = 0; i < SIZE; i++) {
nums[i] *= -i;
printf("CHILD: %d ", nums[i]); /* LINE X */
}
}
// if pid > 0 the the current process is parent process
else if (pid > 0)
{
// wait(NULL) functions tells parent to wait for child process to complete
// if wait(NULL) isn't used then the parent process will execute first
// and LINE Y will be printed first because
// LINE Y is a part of Parent Process
wait(NULL);
for (i = 0; i < SIZE; i++)
printf("PARENT: %d ", nums[i]); /* LINE Y */
}
return 0;
}
The given program shows the working of Parent and child Process
Output: