Pract 2: System Calls (fork(), wait()) in C Language.


fork()
When the fork system call is executed, a new process is created which consists of a copy of the
address space of the parent. The return code for fork is zero for the child process and the process
identifier of child is returned to the parent process.

On success, both processes continue execution at the instruction after the fork call.
On failure, -1 is returned to the parent process.

fork() – Sample Code

fork-example

Implementation of fork() system call using C program.

Pract2a.c

#include <sys/types.h>
main()
{
pid_t pid;
pid = fork();
if (pid == 0)
printf(“\n I’m the child process”);
else if (pid > 0)
printf(“\n I’m the parent process. My child pid is %d”, pid);
else
perror(“error in fork”);
}

Commands: # gcc –o pr pract2a.c
# ./pr

*******************************************************************************

wait() 

The wait system call suspends the calling process until one of its immediate children terminates. If the call is successful, the process ID of the terminating child is returned.

Zombie process—a process that has terminated but whose exit status has not yet been received by its parent process or by init.

pid_t wait(int *status); where status is an integer value where the UNIX system stores the value returned by child process.

Implementation of wait() system call using C program.

Pract2b.c
#include <stdio.h>
void main()
{
int pid, status;
pid = fork();
if(pid == -1)
{
printf(“fork failed\n”);
exit(1);
}
if(pid == 0)
{
/* Child */ printf(“Child here!\n”);
}
else
{
/* Parent */ wait(&status);
printf(“Well done Child!\n”);
}
}

Commands: # gcc –o pr pract2b.c
# ./pr

Leave a comment