Tuesday, May 5, 2009

Fork() example





the fork() is a system call commonly used in Unix/Linux system. the idea is to spawn/create child process. when a program executes the fork() call,let call that program 'parent' and the new created process will be called as 'child'

the fork() when successfully executes, return the child's pid to the parent and return 0 to the child. Now,why the fork() return child's pid to the parent? to hav parent know so that tracking become simple.

In the case of failure the fork() return -1 ,the perror() display error message according to the types of errors encountered.
The errors in executing the fork() are
1) EAGAIN
The system lacked the necessary resources to create another process, or the system-imposed limit on the total number of processes under execution system-wide or by a single user {CHILD_MAX} would be exceeded.

2) ENOMEM
Insufficient storage space is available.

lets peep at the example,well it is a complex but nevertheless u need to know all this..Actually the below code is important...documantation is there...

the reason i omit <> is tht it is the syntax of html..

#include unistd.h /* Symbolic Constants */
#include sys/types.h /* Primitive System Data Types */
#include errno.h /* Errors */
#include stdio.h /* Input/Output */
#include sys/wait.h /* Wait for Process Termination */
#include stdlib.h /* General Utilities */

int main()
{
pid_t childpid; /* variable to store the child's pid */
int retval; /* child process: user-provided return code */
int status; /* parent process: child's exit status */

/* only 1 int variable is needed because each process would have its
own instance of the variable
here, 2 int variables are used for clarity */

/* now create new process */
childpid = fork();

if (childpid >= 0) /* fork succeeded */
{
if (childpid == 0) /* fork() returns 0 to the child process */
{
printf("CHILD: I am the child process!\n");
printf("CHILD: Here's my PID: %d\n", getpid());
printf("CHILD: My parent's PID is: %d\n", getppid());
printf("CHILD: The value of my copy of childpid is: %d\n", childpid);
printf("CHILD: Sleeping for 1 second...\n");
sleep(1); /* sleep for 1 second */
printf("CHILD: Enter an exit value (0 to 255): ");
scanf(" %d", &retval);
printf("CHILD: Goodbye!\n");
exit(retval); /* child exits with user-provided return code */
}
else /* fork() returns new pid to the parent process */
{
printf("PARENT: I am the parent process!\n");
printf("PARENT: Here's my PID: %d\n", getpid());
printf("PARENT: The value of my copy of childpid is %d\n", childpid);
printf("PARENT: I will now wait for my child to exit.\n");
wait(&status); /* wait for child to exit, and store its status */
printf("PARENT: Child's exit code is: %d\n", WEXITSTATUS(status));
printf("PARENT: Goodbye!\n");
exit(0); /* parent exits */
}
}
else /* fork returns -1 on failure */
{
perror("fork"); /* display error message */
exit(0);
}
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.