Monday, June 30, 2008

Implementation of producer-consumer problem using C in Linux

Implementation of producer-consumer problem using C in Linux


/* File name: th1.c */
/* Compile: gcc -lpthread -o th1 th1.c */
/* Run: ./th1 */
#include "pthread.h"
#include "stdio.h"

#define N 6
int c=0;
int buf[N];
int in,out;
void * f1(void *m);
int main(){
pthread_t th;
int d,flag=0;
pthread_create(&th,NULL,f1,NULL);
while(1){
sleep(1);
printf("\nEnter the data : ");
scanf("%d",&d);
flag=0;
while(c==N){
if(flag==0)
printf("\nFull!\n");
flag=1;
} //buffer is full
buf[in]=d;
in=(in+1)%N;
c=c+1;
}
return 0;
}
void * f1(void *m){
int d,flag=0;
while(1){
sleep(3);
flag=0;
while(c==0){
if(flag==0)
printf("\nEmpty!\n");
flag=1;
}
d=buf[out];
printf("\nConsumed item : %d",d);
out=(out+1)%N;
c=c-1;
}}



Monday, June 23, 2008

Using fork in Linux/Unix

Using fork in Linux/Unix :-

A useful way of creating processes is by using fork, but you must take care to keep track of child processes, here is an example of fork written in c.


include int files "sys/types.h", "unistd.h", and "stdio.h".

int main()
{
pid_t id;
char *message;
int n;
printf("fork program startingn");
id = fork();
switch(id) {
case -1:
exit(1);
case 0:
message = "this is the child process";
n = 3;
break;
default:
message = "this is the parent process";
n = 6;
break;
}
for(; n > 0; n-)
{
puts(message);
sleep(1);
}
exit(0);
}


save it as fork1.c and now lets compile this small fork program using the GNU C compiler, now just use the following command: cc -o fork1 fork1.c
Now you can run it : fork &