#include #include #include #include typedef struct _MESSAGE { long nMsgType; char sText[ 30 ]; } MESSAGE, *PMESSAGE; #define MAX_MESSAGE sizeof( MESSAGE ) #define MSGKEY 100 void Child( int nMessages ); void Parent( int nMessages ); void MilliSleep( int nMilliSec ); int g_msgid; int main( int argc, char* argv[] ) { int nMessages = 100; g_msgid = msgget( MSGKEY, 0644 | IPC_CREAT ); if ( -1 == g_msgid ) { perror( "msgget" ); exit( EXIT_FAILURE ); } if ( argc > 1 ) { nMessages = atoi( argv[ 1 ] ); if ( nMessages < 1 ) nMessages = 1; } setbuf( stdout, NULL ); if ( 0 == fork() ) Child( nMessages ); else { Parent( nMessages ); wait( 0 ); /* remove the queue from the system */ if ( -1 == msgctl( g_msgid, IPC_RMID, NULL ) ) perror( "msgctl" ); } return 0; } void Child( int nMessages ) { MESSAGE msg; int i; msg.nMsgType = 1; for ( i = 1; i <= nMessages; ++i ) { sprintf( msg.sText, "Line number %d", i ); printf( "Child sending '%s'\n", msg.sText ); if ( -1 == msgsnd( g_msgid, &msg, MAX_MESSAGE, 0 ) ) perror( "child message send" ); /* sleep now and then */ if ( 0 == ( i % 25 ) ) MilliSleep( rand() % 1000 ); } } void Parent( int nMessages ) { MESSAGE msg; int i; msg.nMsgType = 0; for ( i = 0; i < nMessages; ++i ) { if ( -1 != msgrcv( g_msgid, &msg, MAX_MESSAGE, 0, 0 ) ) printf( "Parent got '%s'\n", msg.sText ); else perror( "parent msg receive" ); /* sleep now and then */ if ( 0 == ( i % 20 ) ) MilliSleep( rand() % 500 ); } } void MilliSleep( int nMilliSec ) { struct timespec ts; ts.tv_sec = nMilliSec / 1000000; ts.tv_nsec = ( nMilliSec % 1000 ) * 1000000; nanosleep( &ts, NULL ); }