Saturday, September 1, 2007

forking i.e examples in C (fork program)

forking i.e example in C (fork program)
===============================


/*forking example 1 */
#include<sys/types.h>
main()
{
int i;
int j;
fork();

printf("\n%d\n",getpid());
printf("\n%d\n",getppid());
getchar();

}

/*forking example 2 */
main()
{
int i=fork();
if(i==0)
{
printf("I'm the child.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());
}
else
{
printf("I'm the Parent.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());
wait();
}
exit(0);
}


/*forking example 3 */

main()
{
int i=fork();
if(i==0)
{
printf("I'm the child.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());

sleep(5);

printf("I'm the child.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());
}
else
{
sleep(2);
printf("I'm the Parent.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());
}
}

/*forking example 4 */

#include<sys/types.h>
main()
{
int j;
int pid=fork();
if(pid==0)
for(j=0;j<30000;j++)
printf("\n%10d\tChild",j);

else
for(j=0;j<30000;j++)
printf("\n%10d\tParent",j);
}


/*forking example 5*/

#include<sys/types.h>
main()
{
int j;
if(fork()==0)
{
printf("\nFirst Child Executing");
for(j=0;j<10000;j++)
;
printf("\nFirst Child is dying now\n" );
}
else
{
if(fork()==0)
{
printf("Second Child Executing");
for(j=0;j<10000;j++)
;
printf("\nSecond Child is dying now\n" );
}
else
{

printf("\nI'm the BOSS here\n");
printf("\nThe first child to die is %d\n",wait(0));

for(j=0;j<10000;j++)
;
printf("\nThe Second child to die is %d\n",wait(0));

printf("But nothing is in my hand!\n");
}

}

}

/*forking example 6*/

main()
{
int pid;
int i=10;
pid=fork();
if(pid==0)
{
printf("\nThe value of I in child is \t%d\n",i);
i+=10;
printf("\nThe (inc)value of I in child is \t%d\n",i);

}

else
{
wait(0);
printf("\nThe value of I in parent is \t%d\n",i);
}
}

/*forking example 7*/

main()
{
int i=10;
if(fork()==0)
printf("\nThe address of i in child is %X \n",&i);
else
printf("\nThe address of i in parent is %X \n",&i);

}


/*forking example 8*/

#include<sys/types.h>
main()
{
if(fork()>0)
{
printf("I'm the parent\n");
sleep(10);
}


}


No comments: