Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаб3.docx
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
46.9 Кб
Скачать
      1. Передача сообщений между независимыми процессами (неименованные каналы)

Листинг 2.3. Сервер. msg_server_ChannelCreate.c.

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

#include <errno.h>

#include <signal.h>

#include <unistd.h>

#include <sys/neutrino.h>

int chid;

void SigintHandler( int signo );

int main(int argc, char *argv[])

{

setbuf( stdout, NULL );

signal( SIGINT, SigintHandler);

char receiveBuff[256];

char replyBuff[256];

// Создание канала //

if (( chid = ChannelCreate(0) )==-1) {

printf( "Server: create channel error!\n" );

exit(1);

}

printf( "Server: create channel. CH_ID=%d, PID=%d\n", chid, getpid() );

// Прием сообщений от клиента //

while (1)

{

int rcvid = MsgReceive( chid, receiveBuff, sizeof(receiveBuff), NULL );

switch (rcvid)

{

// Ошибка //

case -1:

printf( "Server: MsgReceive error.\n" );

break;

// Пульс //

case 0:

printf( "Server: Receive pulse.\n" );

break;

// Сообщение //

default:

printf( "Server: Receive msg - <%s>\n", receiveBuff );

sprintf( replyBuff, "Server reply to client RCV_ID=%d", rcvid );

MsgReply( rcvid, EOK, replyBuff, sizeof(replyBuff));

break;

}

}

return EXIT_SUCCESS;

}

void SigintHandler( int signo ) {

// Уничтожение канала //

ChannelDestroy( chid );

exit( EXIT_SUCCESS );

}

Листинг 2.4. Клиент. msg_client_ConnectAttach.c.

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

#include <errno.h>

#include <signal.h>

#include <sys/neutrino.h>

#include <sys/netmgr.h>

void SigintHandler( int signo );

int coid;

int main(int argc, char *argv[])

{

setbuf( stdout, NULL );

signal( SIGINT, SigintHandler);

char sendBuff[256];

char replyBuff[256];

int chid, ownerPid, nd;

chid = atoi( argv[1] );

ownerPid = atoi( argv[2] );

nd = atoi( argv[3] );

// Создание соединения

coid = ConnectAttach( nd, ownerPid, chid, 0, 0 );

if (coid == -1 ){

printf( "Client: ConnectAttach error!" );

exit(2);

}

while (1) {

printf( "Message: " );

scanf( "%s", sendBuff );

if( MsgSend( coid, sendBuff, sizeof(sendBuff), replyBuff, sizeof(replyBuff) )==-1) {

printf( "Client: MsgSend error!" );

exit(3);

}

printf( "Reply msg: <%s>\n", replyBuff );

}

return EXIT_SUCCESS;

}

void SigintHandler( int signo ) {

// Уничтожение соединения //

ConnectDetach( coid );

exit( EXIT_SUCCESS );

}

Результаты:

Сервер

Клиент

$ ./msg_server_ChannelCreate.out

Server: create channel. CH_ID=1, PID=2809891

Server: Receive msg - <hello>

Server: Receive msg - <bye!>

$ ./msg_client_ConnectAttach.out 1 2809891 0

Message: hello

Reply msg: <Server reply to client RCV_ID=2>

Message: bye!

Reply msg: <Server reply to client RCV_ID=2>

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]