Process ID
-
Find out process ID of your command line interpreter.
Try at least following options
- ps
- ps -o ppid,pid,comm
-
echo $$
-
Examine the following program which prints out process id of the current program and its parent process id.
#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { printf("Process ID = %d\n", getpid()); printf("Parent process ID = %d\n", getppid()); return 0; }
Creating a sub-process and running a program
The goal of this exercise is to create a simple program that runs the ping utility for a few seconds.
- Examine the following program which demonstrates the
fork
system call:
#include <stdio.h> int main(void) { printf("Hello world\n"); pid_t p = fork(); switch(p) { case 0: printf("Child is running\n"); break; case -1: perror("fork"); break; default: printf("Parent is running, fork returned %d\n", p); } }
- Using the sleep fuction make chlid process run for several seconds.
- Observe parent process id (PPID) of the child process. Identify the orphan process.
- Make parent process wait for the child process using the wait system call.
- Use wstatus of the wait system call to print exit code of the child process.
- Add sleep into the parent process and make it call wait later than the child process. Identify the zombie process.
- Use execve system call to modify the program above to run ping google.com in the child process.
- Run the program and then use kill program to end the child process.
- Modify the program such that the parent process sends SIGINT signal to the child process using the kill system call. Make the parent process sleep for several seconds before sending the signal.
Homework 4
Thematically, this homework is related to the family of functions exec. Use the following code to print out all command-line arguments and environment variables:
int main(int argc, char** argv, char** envp)
{
extern char **environ;
}
To print out the environment variables you can use either envp or environ, both should work on GNU/Linux.
int main(int argc, char** argv, char** envp)
{
extern char **environ;
}