CS 537: Introduction to Operating Systems
Project 0 Solution
C-alesthenics
This part of the assignment is covered in the linked tutorial.
Let's go on a scavenger hunt, man !
- What system call(s) might a process invoke in order to block until a particular child process terminates? waitpid() How about until any child process terminates? wait()
- What system call would I use to open a file? open() What arguments would I use to this call if I wanted to create a new file called foobar? open("foobar", O_CREAT, mode);
- What library function converts an integer to a string? snprintf(), sprintf(), or printf(). The atox operations perform the inverse -- converting a string to an integer; you can also use scanf() to convert a string to an integer.
- What library function searches for a substring of a string? strstr()
- What system call returns the process ID of the current process? getpid() How about the process ID of the current process' parent? getppid()
Raiding the silverware drawer
Example solution for vacation.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc, char *argv[]) {
if(fork() == 0) {
/* we're in the child process here */
printf("Are we there yet?\n");
} else {
/* we're in the parent process here */
printf("Don't make me come back there!\n");
}
exit(0);
}
Example solution for vacation2.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc, char *argv[]) {
int pid;
pid_t my_pid, parent_pid;
pid = fork();
/* we have already forked at this point;
note that these calls will (of course)
return different values in the parent
and in the child */
my_pid = getpid();
parent_pid = getppid();
if(pid == 0) {
/* we're in the child process here */
printf("pid: %i; parent pid: %i Are we there yet?\n", my_pid, parent_pid);
} else {
/* we're in the parent process here */
/* wait for child process to terminate.
We don't care about its exit status.
In a real program, we would, and we
would also check the return value of
waitpid to ensure that no errors occured. */
waitpid(pid, NULL, 0);
printf("pid: %i; parent pid: %i Don't make me come back there!\n", my_pid, parent_pid);
}
exit(0);
}
- Is this program deterministic? That is, can we be sure that this program will always produce the same output? If you have the parent process wait for the child to terminate before the parent calls printf, it is deterministic; otherwise, it is not.
- If you answered “yes” to the preceding question, explain why. If you answered “no”, please explain why and describe how you would change the program to make it deterministic. See above; basically, unless the parent process waits for the child to terminate, we have no guarantees about which will be scheduled first.
