I have been executed 'n' times

on Thursday, November 19, 2009

Write a code which outputs the number 'n' , which represent no. of times it had been run.
eg. running it for first time it should give 1
for 2nd time it should give 2.






















SOLUTION
#include sys/types.h
#include sys/ipc.h
#include sys/shm.h
#include unistd.h
#include cstdlib
#include cstdio
#define SHMKEY 5678L
using namespace std;

int main()
{
int shmid;
int *no_of_executions;
char *shmptr;



if ( (shmid=shmget(SHMKEY,sizeof(int),IPC_CREAT|IPC_EXCL|0666)) > 0 )
{
if((shmptr =(char*)shmat(shmid,0,0))==(char *)-1)
{
perror("failed to attah shared memory");
exit(-1);
}
no_of_executions=(int*)shmptr;
*no_of_executions=1;
printf("%d\n", *no_of_executions);
}
else
{

if ((shmid=shmget(SHMKEY,sizeof(int),0)) == -1)
{
perror("failed to create shared memory");
exit(-1);
}
if((shmptr =(char*)shmat(shmid,0,0))==(char *)-1)
{
perror("failed to attah shared memory");
exit(-1);
}
no_of_executions=(int*)shmptr;
++*no_of_executions;
printf("%d\n", *no_of_executions);

}


return 0;
}

2 comments:

Anonymous said...

nice man. but we can also do this by file handling

hifun said...

@ above
yes, u r right. And also solution provided above may be OS dependent.

Post a Comment