Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

Process Control and File I/O

Lab #4 – Process Control and File I/O
Part I
Read the following programs and write down the expected results. Then run the programs
to check the results. Make sure you understand why. To pass the lab test, you may be
asked for the results of similar programs. For this exercise, it is assumed that all fork()
function calls are successful, and the part of code for checking whether a fork() call is
successful or not is omitted.
#include
#include
#include
int main() {
fork();
fork();
fork();
printf(“%d\n”, getpid());
}
———————————————
#include
#include
#include
int main() {
if (fork() == 0)
fork();
else {
fork();
fork();
printf(“%d\n”, getpid());
}
}
———————————————
#include
#include
#include
int main() {
60-256 System Programming Dr. Chen
2
if (fork() == 0)
fork();
else {
fork();
fork();
}
printf(“%d\n”, getpid());
}
———————————————
#include
#include
#include
int main() {
if (fork() == 0)
fork();
else {
fork();
fork();
exit(0);
}
printf(“%d\n”, getpid());
}
Part II
Use fork() to create a child process.
• The parent process checks the first command line argument. If it is not an integer
number between 1 and 10 (inclusive), the parent process will print out an error
message; otherwise, it will write the number into a file called data.dat.
• The child process reads the number from the file and prints out its factorial
number. You need to make sure that the child process will read the file only after
the parent has finished writing into it.
You can use library functions to convert a string into an integer. You can use library I/O
call to print error message. With file data.dat, you must use system call I/O (no library
I/O call allowed).

Answer:

PART 1

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
fork();
fork();
fork();
printf("%d\n", getpid());
}

PART 2

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
if (fork() == 0)
fork();
else {
fork();
fork();
printf("%d\n", getpid());
}
}

PART 3

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
if (fork() == 0)
fork();
else {
fork();
fork();
}
printf("%d\n", getpid());
}

PART 4

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
if (fork() == 0)
fork();
else {
fork();
fork();
exit(0);
}
printf("%d\n", getpid());
}

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!