CS4315 Operating Systems
Lab 2: Linux Processes
This lab assignment contains three questions.
To submit this lab assignment, please use a Word document to
include the
screenshots and write your answer.
1. Run the following C program, and submit a screenshot of the
result.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main( )
{
pid_t pid;
if ( (pid = fork()) == 0 )
{
printf (“I am the child, my pid = %d and my parent
pid = %d\n”, getpid(), getppid());
exit(0);
}
if (pid < 0)
{
fprintf (stderr, “fork failed\n”);
exit(1);
}
printf(“I am the parent, my pid = %d\n”, getpid());
}
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
1st program out put:
2nd program output:
First using fork () system call get the pid then if pid==0
Then executes the first for loop for (i=0;i<size;i++)
nums[0] =nums [0] * -i;
i.e nums[0]=0*-0=0
it gives the out put CHILD : 0
nums[1] =nums [1] * -i;
i.e nums[1]=1*-1=-1
it gives the out put CHILD : -1
nums[2] =nums [2] * -i;
i.e nums[2]=2*-2=-4
it gives the out put CHILD : -4
nums[3] =nums [3] * -3;
i.e nums[3]=3*-3=-9
it gives the out put CHILD : -9
nums[4] =nums [4] * -4;
i.e nums[4]=4*-4=-16
it gives the out put CHILD : -16
in the second for loop it gives the output
PARENT : 0 PARENT : 1 PARENT : 2 PARENT : 3 PARENT : 4
Simply it reads the every i value and prints the i value
3 rd program output:
it terminates in the 1st condition.
Get Answers For Free
Most questions answered within 1 hours.