IPC Memory Share - C Program - Why not exiting for(;;) ??
Hi all!
I have two C program sources: PROC1.C and PROC2.C. Both share the same memory region, defined by t_info struct.
I only would like to know why it does NOT leave the FOR's when I type "sair" in the command line.
To run the program, you need pthread library and start first PROC1.C.
Tks a lot!
BP
/********* PROC1.C ********/
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/errno.h>
#include <pthread.h>
typedef struct
{
int ok1, ok2;
char texto1[128], texto2[128];
}t_info;
extern int errno;
char *pgname;
t_info *info;
void * thread_escreve( void * arg ) {
for(;; ) {
printf("Digite um texto (proc1): ");
fgets( info->texto1, 128, stdin );
if( strcmp( info->texto1, "sair" ) == 0 ) {
info->ok1 = -1;
break;
} else {
info->ok1 = 1 ;
}
}
}
int main (int argc, char *argv[])
{
int md;
pthread_t tid;
pgname = argv[0];
// Criando a area de memoria compartilhada.
if ((md = shmget(8752, sizeof(t_info),0700|IPC_CREAT|IPC_EXCL)) == -1)
{
if (errno == EEXIST)
fprintf (stderr, "%s:Area de memoria ja existe.", pgname);
else
perror (pgname);
exit (-1);
}
// Mapeando a area de memoria compartilhada
if ((info = shmat (md, NULL, 0)) == (void *) -1)
{
perror (pgname);
exit (-1);
}
pthread_create( &tid, NULL, thread_escreve, NULL );
info->ok2 = 0;
for( ;; ) {
while (info->ok2 == 0)
/* aguarda */;
if( info->ok2 == -1 )
break;
printf ("Texto (proc1): %s", info->texto2);
info->ok2 = 0;
}
pthread_join( tid, NULL );
// Desfazendo o mapeamento
if (shmdt ((char *) info) == -1)
{
perror (pgname);
exit (-1);
}
// Destruindo a area de memoria
if (shmctl (md, IPC_RMID, NULL) == -1)
{
perror (pgname);
exit (-1);
}
}
/*********** PROC2.C ***********/
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/errno.h>
#include <pthread.h>
typedef struct
{
int ok1, ok2;
char texto1[128], texto2[128];
}t_info;
extern int errno;
char *pgname;
t_info * info;
void * thread_escreve( void * argumento ) {
for( ;; ) {
printf( "Digite um texto (proc2): " );
fgets( info->texto2, 128, stdin );
if( strcmp( info->texto2, "sair" ) == 0 ) {
info->ok2 = -1 ;
break;
} else {
info->ok2 = 1 ;
}
}
}
int main (int argc, char *argv[])
{
int md;
pthread_t tid;
pgname = argv[0];
// Obtendo o identificador da area de memoria compartilhada.
if ((md = shmget(8752, sizeof(t_info),0700)) == -1)
{
perror (pgname);
exit (-1);
}
// Mapeando a area de memoria compartilhada
if ((info = shmat (md, NULL, 0)) == (void *) -1)
{
perror (pgname);
exit (-1);
}
info->ok1 = 0;
pthread_create( &tid, NULL, thread_escreve, NULL );
for( ;; ) {
while( info->ok1 == 0 ) ;
if( info->ok1 == -1 )
break;
printf( "Texto (proc2): %s", info->texto1 );
info->ok1 = 0 ;
}
pthread_join( tid, NULL );
// Desfazendo o mapeamento
if (shmdt ((char *) info) == -1)
{
perror (pgname);
exit (-1);
}
}
Last edited by brunnopessoa; 09-03-2004 at 11:50 PM.
|