Question: Comment this C code With as much detail as possible and describe what the program is doing CODE: #include #include #include #include #include #include #include

Comment this C code With as much detail as possible and describe what the program is doing

CODE:

#include

#include

#include

#include

#include

#include

#include

#include

int id;

struct Mesg{//struct that contains message,count, and token

char Message[40];

int count;

char token[10][20];

char sorttoken[10][20];

};

#define KEY ((key_t)(713))

#define SEGSIZE sizeof(struct Mesg)

void cleanup(int sigtype){

shmdt(0);

printf(" Terminating ");

execlp("ipcrm","ipcrm","-M","713",(char*)(0));

printf("ERROR!");

exit(0);

}

int main(){

int i,j;

int count;

char *token;

char tmp[20];

struct Mesg *msg;

struct shmid_ds shmbuf;

signal(SIGINT,cleanup);

signal(SIGQUIT,cleanup);

id=shmget(KEY,SEGSIZE,IPC_CREAT|0666);

if(id<0){

perror("shmget failed 1 ");

exit(1);

}

msg=(struct Mesg*) shmat(id,0,0);

if(msg<=(struct Mesg *)(0)){

perror("shma failed 2 ");

exit(1);

}

msg->count=0;

printf("Parent : Enter a Message : ");

count=read(0,msg->Message,40);

if(count<=0){

printf("read failed or no text entered! ");

exit(0);

}

msg->Message[count-1]='\0';

printf("Parent pid = %d, Message readed:'%s' ",getpid(),msg->Message);

printf("Just before forking, pid = %d ",getpid());

if(fork()==0){

printf("fork 1 ");

msg->count=1;

for(i=0;i

if(msg->Message[i]==' ')

msg->count++;

printf("token count = %d ",msg->count);

exit(0);

}else

if(fork()==0){

sleep(1);

printf("fork 2 ");

i=0;

token=strtok(msg->Message," ");

while(token!=NULL){

strcpy(msg->token[i],token);

i++;

token=strtok(NULL," ");

}

printf("Tokens : ");

for(i=0;icount;i++){

printf("%s ",msg->token[i]);

}

printf("Tokens end ");

exit(0);

}else

if(fork()==0){

sleep(3);

printf("fork 3 ");

for(i=0;icount;i++){

strcpy(tmp,msg->token[i]);

strcpy(msg->sorttoken[i],tmp);

}

for(i=msg->count-1;i>=0;i--){

for(j=0;j

if(strcmp(msg->sorttoken[j],msg->sorttoken[j+1])>0){

strcpy(tmp,msg->sorttoken[j]);

strcpy(msg->sorttoken[j],msg->sorttoken[j+1]);

strcpy(msg->sorttoken[j+1],tmp);

}

}

}

printf("Sorted tokens : ");

for(i=0;icount;i++){

printf("%s ",msg->sorttoken[i]);

}

printf("Sorted tokens end ");

exit(0);

}

for(i=0;i<3;i++)

wait(0);

printf("Press Ctrl-C (or) Ctrl-\\ to clean up the memory and exit. ");

for(;;);

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!