Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Computer Science Fork in C Program - Notes - Prof Neelima Singh, Study notes of C programming

Detailed informtion about Fork in C Program , orphan process, processes, Forking multiple child processes in C program , Programms.

Typology: Study notes

2010/2011

Uploaded on 09/06/2011

nirmalya
nirmalya 🇮🇳

4.5

(2)

17 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Fork in C program
In this example, we will write a simple C program which will fork a child process. The "fork()" function will be used to do this.
fork() returns 0 to the child process and the child pid to the parent process. Our parent process and child process will count up to
ten. For process switching by operating system, we will observe in the output that the processes are not printing serially, rather
they are printing in turn.. Type in the following C program in your editor:
// forking.c
#include <stdio.h>
int main(void)
{
// Variable to hold the process id
int pid;
// Fork the process and get the process id in "pid"
pid = fork();
// Check the value of pid
if(pid == 0)
{
/* Child process:
* When fork() returns 0, we are in
* the child process.
* Here we count up to ten, one each second.
*/
int j;
for(j=0; j < 10; j++)
{
printf("child: %d\n", j);
// Force the process to sleep for one second
sleep(1);
}
_exit(0); /* Note that we do not use exit() because it is not
async-signal safe */
}
else if(pid > 0)
{
/* Parent process:
* Otherwise, we are in the parent process.
* Again we count up to ten.
*/
int i;
for(i=0; i < 10; i++)
{
printf("parent: %d\n", i);
// Force the process to sleep for one second
sleep(1);
}
}
else
{
/* Error handling. */
fprintf(stderr, "couldn't fork");
exit(1);
}
}
pf3
pf4
pf5

Partial preview of the text

Download Computer Science Fork in C Program - Notes - Prof Neelima Singh and more Study notes C programming in PDF only on Docsity!

Fork in C program

In this example, we will write a simple C program which will fork a child process. The "fork()" function will be used to do this. fork() returns 0 to the child process and the child pid to the parent process. Our parent process and child process will count up to ten. For process switching by operating system, we will observe in the output that the processes are not printing serially, rather they are printing in turn.. Type in the following C program in your editor: // forking.c #include <stdio.h> int main(void) { // Variable to hold the process id int pid; // Fork the process and get the process id in "pid" pid = fork(); // Check the value of pid if(pid == 0) { /* Child process:

  • When fork() returns 0, we are in
  • the child process.
  • Here we count up to ten, one each second. / int j; for(j=0; j < 10; j++) { printf("child: %d\n", j); // Force the process to sleep for one second sleep(1); } _exit(0); / Note that we do not use exit() because it is not async-signal safe / } else if(pid > 0) { / Parent process:
  • Otherwise, we are in the parent process.
  • Again we count up to ten. / int i; for(i=0; i < 10; i++) { printf("parent: %d\n", i); // Force the process to sleep for one second sleep(1); } } else { / Error handling. */ fprintf(stderr, "couldn't fork"); exit(1); } }

Everything on the right of a "//" is a single line comment and everything in between a pair of "/" and "/" are multi-line comments. Comments are not part of the program. Save the file as "forking.c" and then from the terminal compile and build it with the following command: {cs1:~} gcc - o forking forking.c {cs1:~} ls - l

  • rwx--x--x 1 mfh062000 sn 7080 Oct 15 13:58 forking
  • rw-r----- 1 mfh062000 sn 937 Oct 15 13:51 forking.c This will create an executable named "forking" with execute permissions. This can be seen from the output of "ls - l". Run the program:: {cs1:~} ./forking parent: 0 child: 0 parent: 1 child: 1 parent: 2 child: 2 parent: 3 child: 3 parent: 4 child: 4 child: 5 parent: 5 parent: 6 child: 6 child: 7 parent: 7 child: 8 parent: 8 parent: 9 child: 9

Forking multiple child processes in C program

In C program, the task of creating multiple child processes is simple. After a pid check for parent process, we simply create another process. Here is an example which creates two child processes: // forking2.c #include <stdio.h> int main(void) { // Variable to hold the process id int pid; // Fork the process and get the process id in "pid" pid = fork(); // Check the value of pid if(pid == 0) { /* Child process:

  • When fork() returns 0, we are in
  • the child process.
  • Here we count up to ten, one each second. */ int j;

{cs1:~} gcc - o forking2 forking2.c {cs1:~} ./forking child: 0 child: 0 parent: 0 child: 1 child: 1 parent: 1 parent: 2 child: 2 child: 2 child: 3 child: 3 parent: 3 parent: 4 child: 4 child: 4 child: 5 child: 5 parent: 5 parent: 6 child: 6 child: 6 child: 7 child: 7 parent: 7 parent: 8 child: 8 child: 8 child: 9 parent: 9 child: 9 The output will be similar to above. It may not be the same because it depends on process scheduling.

On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has

completed execution but still has an entry in the process table. This entry is still needed to allow the process that

started the (now zombie) process to read its exit status. The term zombie process derives from the common

definition of zombie—an undead person. In the term's colorful metaphor, the child process has died but has not yet

been reaped. Also, unlike normal processes, the kill command has no effect on a zombie process.

When a process ends, all of the memory and resources associated with it are deallocated so they can be used by

other processes. However, the process's entry in the process table remains. The parent can read the child's exit status

by executing the wait system call, at which stage the zombie is removed. The wait call may be executed in

sequential code, but it is commonly executed in a handler for the SIGCHLD signal, which the parent receives

whenever a child has died.

After the zombie is removed, its process ID and entry in the process table can then be reused. However, if a parent

fails to call wait, the zombie will be left in the process table. In some situations this may be desirable, for example if

the parent creates another child process it ensures that it will not be allocated the same process ID.

A zombie process is not the same as an orphan process. An orphan process is a process that is still executing, but

whose parent has died. They do not become zombie processes; instead, they are adopted by init (process ID 1),

which waits on its children.

Zombies can be identified in the output from the Unix ps command by the presence of a “Z” in the “STAT” column.

Zombies that exist for more than a short period of time typically indicate a bug in the parent program, or just an

uncommon decision to reap children (see example). If the parent program is no longer running, zombie processes

typically indicate a bug in the operating system. As with other leaks, the presence of a few zombies is not worrisome

in itself, but may indicate a problem that would grow serious under heavier loads. Since there is no memory

allocated to zombie processes except for the process table entry itself, the primary concern with many zombies is not

running out of memory, but rather running out of process ID numbers.

To remove zombies from a system, the SIGCHLD signal can be sent to the parent manually, using the kill

command. If the parent process still refuses to reap the zombie, the next step would be to remove the parent process.

When a process loses its parent, init becomes its new parent. Init periodically executes the wait system call to reap

any zombies with init as parent.

Synchronously waiting for specific child processes in a (specific) order may leave zombies present longer than the above-mentioned “short period of time”. It is not necessarily a program bug, but rather a programming paradigm that is not seen very often in the wild. #include <sys/wait.h> #include <stdlib.h> #include <unistd.h> int main(void) { pid_t pids[10]; int i; for (i = 9; i >= 0; --i) { pids[i] = fork(); if (pids[i] == 0) { sleep(i+1); _exit(0); } } for (i = 9; i >= 0; --i) waitpid(pids[i], NULL, 0); return 0; }

oAn orphan process is a computer process whose parent process has finished or terminated, though itself remains

running.

In a Unix-like operating system any orphaned process will be immediately adopted by the special init system

process. This operation is called re-parenting and occurs automatically. Even though technically the process has the

"init" process as its parent, it is still called an orphan process since the process that originally created it no longer

exists.

A process can be orphaned unintentionally, such as when the parent process terminates or crashes. The process

group mechanism in most Unix-like operation systems can be used to help protect against accidental orphaning,

where in coordination with the user's shell will try to terminate all the child processes with the SIGHUP process

signal, rather than letting them continue to run as orphans.

A process may also be intentionally orphaned so that it becomes detached from the user's session and left running in

the background; usually to allow a long-running job to complete without further user attention, or to start an

indefinitely running service. Under Unix, the latter kinds of processes are typically called daemon processes. The

Unix nohup command is one means to accomplish this.

With remote invocation, a server process is also said to be orphaned when the client that initiated the request

unexpectedly crashes after making the request while leaving the server process running. These orphaned processes