The UNIX and Linux Forums  
Olá e boas-vindas de Estados Unidos para o UNIX e Linux Forum! Obrigado por visitar e fazer parte da nossa comunidade global.

Go Back   O UNIX e Linux Forum > Top Fóruns > Alto Nível de programação
.
google unix.com



Alto Nível de programação Post perguntas sobre C, C + +, Java, SQL, e outras linguagens de programação aqui.

Mais UNIX e Linux Fórum Tópicos Você pode achar Helpfull
Fio Thread Starter Fórum Respostas Última postagem
impossibilitado de efetuar login no gdm, urgente ajuda necessária! pls wrapster Programação Shell Script e 0 04-25-2008 01:48
urgentemente necessária manish1 Programação Shell Script e 0 03-13-2008 05:09
Urgente ajuda necessária skyineyes UNIX para Dummies Perguntas & Respostas 5 06-19-2007 04:31
urgente ajuda necessária. Lote Programação Shell Script e 4 12-08-2006 11:31
urgente ajuda necessária! guhas Programação Shell Script e 0 09-10-2005 02:01

 
English Japanese Spanish French German Portuguese Italian Dutch Swedish Russian Norwegian Hungarian Hebrew Danish Bulgarian Greek Powered by Powered by Google
 
Linkback Thread Tools Pesquisar este Thread Rate Thread Display Modes
  #1 (permalink)  
Old 05-19-2005
mgchato's Avatar
mgchato mgchato is offline
Usuário
  
 

Join Date: May 2005
Posts: 7
Mensagem filas e coordenação programas novamente ...

Olá todos!

Eu estou supostamente para desenhar e implementar um conjunto de programas que permitem que os usuários conectado a um host para enviar mensagens uns aos outros.

Já começou com um programa que mensagens devem ser feitos de um servidor e um cliente (Thanx a lot for your help maçarico). Eu estou supostamente para adicionar este programa a uma coordenação programa. O coordenador deve aceitar as mensagens de clientes e encaminhá-los a todos os clientes acompanham. Estou também esperado para adicionar um comando para o cliente que lhe permite iniciar sessão para um determinado arquivo de texto para todas as mensagens recebidas.

Estou a pensar que uma boa maneira de lidar com o seu seria para encapsular a mensagem fila em um módulo que os clientes e coordenador pode chamar, mas a coisa é que eu não tenho a mínima idéia por onde começar! Do u guys know quaisquer livros ou sites onde posso obter amostras de código e de explicações? Acho que a única maneira para mim de aprender é através de exemplos ...

Quantos PD. C arquivos que eu preciso?

Thanx a lot for your help!

Oh, e aqui está o meu mensageiro programas:

Código:
/*q.h*/
#ifndef Q_H
	#define Q_H
	#define QKEY ftok("q.h",1)
	#define MSGSZ 128

	#ifdef DEBUG
		#define DEBUG_PRINT(...) fprintf(stderr,__VA_ARGS__)
		/* this __VA_ARGS__ thing allows a macro to
		take a varialble number of arguments */
	#else
		#define DEBUG_PRINT(...) /* __VA_ARGS__ */
	#endif

	int init_queue();
	int exchange_pids();
	void remove_queue();
	int send_mesg(char*,int);
	int send_mesg_signal(char*,int);
	int recv_mesg(char*,int);
#endif



/*signalmsg.c*/
#include<signal.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include"q.c"
#include"q.h"

int cnt;
void hndlr(int);

main()
{
        struct sigaction buf;
        char msg[MSGSZ];
        int stop=0,n;
        sigfillset(&buf.sa_mask);
        buf.sa_flags=0;
        buf.sa_handler=hndlr;
        sigaction(SIGUSR1,&buf,NULL);
        sigaction(SIGINT,&buf,NULL);
        init_queue();
        exchange_pids();
        
while(!stop)
        {
                printf("\nEnter message: ");
                while (-1 == (n=read(0,msg,MSGSZ-1) ))
                {
                        if (errno != EINTR )
                        {
                           perror("read");
                           send_mesg("bye\n",0);
                           exit(1);
                        }
                        for(;cnt>0;cnt--)
                        {
                           recv_mesg(msg,0);
                           printf("\nReceived Message: %s\n", msg);
                           if (0==strcmp(msg,"bye\n"))
                           {
                                remove_queue();
                                exit(0);
                           }
                        }
                        printf("\nEnter message: ");
                }
                msg[n]=0;
                send_mesg_signal(msg,0);
                if (0==strcmp(msg,"bye\n"))
                        stop=1;
        }
        return 0;
}

void hndlr(int sig)
{
        DEBUG_PRINT("Caught signal: %d\n",sig);
        switch(sig)
        {
        case SIGUSR1:   DEBUG_PRINT("USR1 branch\n");
                        cnt++;
                        break;
        case SIGINT:    DEBUG_PRINT("SIGINT branch\n");
                        send_mesg_signal("bye\n",0);
                        exit(0);
                        break;
        default:        fprintf(stderr,"Yikes how did I get here?!!!\n");
                        exit(1);
        }

}



/*q.c*/
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<unistd.h>
#include<signal.h>
#include<errno.h>
#include"q.h"

struct mymsg
{
        long mtype;
        char mtext[MSGSZ];
};

static int qid;
static int channel_no;
static pid_t remote_pid;

void remove_queue()
{
        msgctl(qid,IPC_RMID,0);
}

int init_queue()
{
        char  msg[MSGSZ];
        int rv;
        if( -1 != ( qid = msgget(QKEY,IPC_CREAT|IPC_EXCL|0600) ))
        {
                /* am entity A using channel 1 */
                channel_no=1;
                DEBUG_PRINT("Am entity A\n");
                return 0;
        }
        if ( errno != EEXIST )
        {
                perror("MSGGET:");
                return -1;
        }
        if (-1 != ( qid = msgget(QKEY,IPC_CREAT|0600) ))
        {
                /* am entity B using channel 2 */
                 channel_no=2;
                DEBUG_PRINT("Am entity B\n");
                return 0;
        }

        perror("MSGGET:");
        return -1;
}

int exchange_pids()
{
        char msg[MSGSZ];
        if(channel_no==1)
        {
                /* sending PID to other end */
                sprintf(msg,"%d",getpid());
                send_mesg(msg,0);
                DEBUG_PRINT("My pid is %s\n",msg);
                /* grab pid from other end */
                recv_mesg(msg,0);
                sscanf(msg,"%d",&remote_pid); 
                DEBUG_PRINT("Received PID is %s\n",msg);
        }
        else
        {
                /* grab pid from other end */
                recv_mesg(msg,0);
                sscanf(msg,"%d",&remote_pid);
                DEBUG_PRINT("Received PID is %s\n",msg);
                
                /* sending PID to other end */
                sprintf(msg,"%d",getpid());
                send_mesg(msg,0);
                DEBUG_PRINT("My pid is %s\n",msg);
        }
        return remote_pid;
}

int recv_mesg(char *msg, int nb)
{
        struct mymsg m;
        int options=0,len;
        int recv=((channel_no==1)?2:1);
        DEBUG_PRINT("Receiving on %d\n",recv);
        if (nb) options|=IPC_NOWAIT;
        if( -1==(len=msgrcv(qid,&m,MSGSZ,recv,options)))
                return -1;
        strcpy(msg,m.mtext);
        return len;
}

int send_mesg(char* msg,int nb)
{
        struct mymsg m;
        int options,len;
        m.mtype=channel_no;
        strcpy(m.mtext,msg);
        len=strlen(msg)+1;
        options=0;
        if (nb) options|=IPC_NOWAIT;
        DEBUG_PRINT("Sending type %d\n",m.mtype);
        return msgsnd(qid,&m,len,options);
}

int send_mesg_signal(char*msg,int nb)
{
        int rv;

        rv=send_mesg(msg,nb);
        kill(remote_pid,SIGUSR1);
        return rv;
}

Última edição por mgchato; em 05/19/2005 04:34..
 

Marcadores

Thread Tools Pesquisar este Thread
Pesquisar este Thread:

Pesquisa Avançada
Display Modes Esta taxa Thread
Esta taxa Thread:

Destacamento Regimento
Você não pode postar novas threads
Você não pode postar respostas
Você não pode postar anexos
Você não pode editar suas postagens

BB code é Ligado
Smilies são Ligado
[IMG] código é Ligado
Código HTML é Desligado
Trackbacks são Ligado
Pingbacks são Ligado
Refbacks são Ligado




Todos os horários são GMT -4. A hora é agora 06:41.


Powered by: vBulletinCopyright © 2000 - 2006, Jelsoft Enterprises Limited. Língua Traduções Powered by .
vBCredits v1.4 Copyright © 2007 - 2008, PixelFX Studios
O UNIX e Linux Fóruns Content Copyright © 1993-2009. Todos os Direitos Reserved.Ad Gestão por RedTyger

Content Relevant URLs por vBSEO 3.2.0