1: #include <stdio.h>
2: #include <stdlib.h>
3: #include <unistd.h>
4: #include <sys/types.h>
5: #include <sys/stat.h>
6: #include <sys/wait.h>
7: #include <sys/msg.h>
8: #include <sys/ipc.h>
9: #include <string.h>
10:
11: const unsigned int MSG_SIZE = 56;
12:
13: struct msg_struct
14: {
15: long int type;
16: char data[MSG_SIZE];
17: };
18:
19:
20: int main( void )
21: {
22: int pid;
23: int msg_id;
24: struct msg_struct Msg;
25: long int msg_type;
26: char buffer[MSG_SIZE] = {0};
27:
28: // Create message queque
29: msg_id = msgget( (key_t)1234, 0666 | IPC_CREAT );
30: if ( msg_id == -1 )
31: {
32: fprintf( stderr, "msgget failed\n" );
33: exit( EXIT_FAILURE );
34: }
35: // Fork
36: if ( (pid = fork()) < 0 )
37: {
38: fprintf( stderr, "fork failed\n" );
39: exit( EXIT_FAILURE );
40: }
41:
42: //
43: // The child process executes the stuff inside the if.
44: //
45: if ( 0 == pid )
46: {
47: printf( "CHILD> Starting ...\n" );
48: //
49: // Read queque and do somehting again
50: //
51: while ( 1 )
52: {
53: msg_type = 0; // Receive all messages
54: if ( msgrcv( msg_id, (void *)&Msg, MSG_SIZE, msg_type, IPC_NOWAIT ) > 0 )
55: {
56: printf( "CHILD> Received \"%s\" from parent.\n", Msg.data );
57: if ( 0 == strcmp( Msg.data, "quit" ) ) break;
58: }
59: else // do something
60: {
61: sleep( 1 );
62: // printf( "CHILD> Standing up ...\n" );
63: }
64: }
65:
66: printf( "CHILD> Exiting ...\n" );
67: exit( EXIT_SUCCESS );
68: }
69:
70: //
71: // The parent process continous here
72: //
73: printf( "PARENT> Starting ...\n" );
74: //
75: // Write to queque untile we get quit
76: //
77: while ( 1 )
78: {
79: printf( "PARENT> Enter some text ( or quit ): " );
80: fgets( buffer, MSG_SIZE, stdin );
81: Msg.type = 1;
82: strcpy( Msg.data, buffer );
83: Msg.data[strlen( Msg.data) - 1 ] = 0x0;
84:
85: if ( msgsnd( msg_id, (void *)&Msg, MSG_SIZE, IPC_NOWAIT ) == -1 )
86: {
87: fprintf( stderr, "msgsnd failed\n" );
88: exit( EXIT_FAILURE );
89: }
90:
91: if ( 0 == strcmp( Msg.data, "quit" ) ) break;
92: else sleep( 1 );
93: }
94:
95: //
96: // Wait for child to exit
97: //
98: while ( wait( (int *) 0) != pid )
99: {
100: }
101:
102: printf( "PARENT> Exiting ...\n" );
103: exit( EXIT_SUCCESS );
104: }
105:
106:
107: /* OUTPUT:
108:
109: [awilhelm@pluto R2.2 msg_queque]$ ./MSG
110: PARENT> Starting ...
111: CHILD> Starting ...
112: PARENT> Enter some text: Hallo child
113: CHILD> Received "Hallo child" from parent.
114: PARENT> Enter some text: How are you
115: CHILD> Received "How are you" from parent.
116: PARENT> Enter some text: quit
117: CHILD> Received "quit" from parent.
118: CHILD> Exiting ...
119: PARENT> Exiting ...
120: [awilhelm@pluto R2.2 msg_queque]$
121:
122: */
124: