[英]sending data from client to server using named pipe in C linux
我正在嘗試使用C linux中的命名管道將數據表單客戶端發送到服務器。 我想將3件事(消息長度,消息類型和消息)發送到一個結構中,然后將指向該結構的指針發送到服務器。 但是,只有消息長度正在發送,而其他兩件事卻沒有。
這是我的代碼
//client.c
//header files
typedef struct msgclient
{
int msglen;
int msgtype;
char cp[100];
}M1;
int main()
{
M1 *m;
int rdfd, wrfd, numread;
int ans;
m=malloc(sizeof(M1));
do
{
printf("\nEnter message type\n1. YOU WANT TO ENTER DATA\n2. AUTOMATIC DATA\n3. EXIT\nENTER YOUR CHOICE\t");
scanf("%d",&m->msgtype);
switch(m->msgtype)
{
case 1: //memset(buf,'\0',(strlen(buf)+1));
m->msgtype=1;
printf("\nEnter data\t");
getchar();
scanf("%s",&m->cp);
m->cp[strlen(m->cp)]='\0';
m->msglen=strlen(m->cp);
break;
case 2: m->msgtype=2;
strncpy(m->cp,"I am HERE!!",strlen("I am HERE!!"));
m->cp[strlen("I am HERE!!")]='\0';
m->msglen=strlen(m->cp);
break;
case 3: exit(0);
default:printf("\nINVALID CHOICE\nTRY AGAIN\n1. YES \n2. NO\n");
scanf("%d",&ans);
continue;
}
wrfd = open(NP1, O_WRONLY);
numread=write(wrfd, m, sizeof(m));
printf("\nno. of bytes SENT TO the SERVER = %d",numread);
printf("\n%s",m->cp);
printf("\n%d",m->msgtype);
printf("\nSEND AGAIN\n1. YES \n2. NO\t");
getchar();
scanf("%d",&ans);
}while(ans==1);
return 0;
}
現在是server.c
//server.c
//header files
typedef struct msgclient
{
int msglen;
int msgtype;
char cp[100];
}M1;
int main()
{
M1 *m;
int rdfd, wrfd, ret_val, numread;
int ans=1;
m=malloc(sizeof(M1));
ret_val = mkfifo(NP1,0666);
if ((ret_val == -1) && (errno != EEXIST))
{
perror("Error creating the named pipe");
exit (1);
}
ret_val = mkfifo(NP2, 0666);
if ((ret_val == -1) && (errno != EEXIST))
{
perror("Error creating the named pipe");
exit (1);
}
while(ans!=0)
{
rdfd = open(NP1, O_RDONLY);
if((numread = read(rdfd, m, sizeof(m)))==0)
return 0;
printf("\nno. of bytes read from the client = %d\n\n",numread);
fputs(m->cp,stdout);
//printf("message is %s",m->cp);
printf("\nLENGTH = %d\nTYPE = %d\nMESSAGE IS %s \nRECEIVED BY SERVER\n",m->msglen,m->msgtype,m->cp);
printf("\nSENT TO CLIENT\n");
}
return 0;
}
請幫助我。 謝謝 :)
概念上的問題是您正在“將指向該結構的指針發送到服務器”。 客戶端和服務器具有不同的內存空間,並且它們不能共享指針。 您需要發送結構本身。 幸運的是,這幾乎是您在程序中所做的。
具體來說,問題在於:
M1 *m;
m=malloc(sizeof(M1));
.
.
.
numread=write(wrfd, m, sizeof(m));
參數m
是正確的(它是結構),但是您應該將sizeof(m)
更改為sizeof(*m)
,這樣,您發送的字節數與結構中的字節數相同。 您當前的代碼僅發送與指針一樣多的字節。 您還需要在服務器上的相應read
更改緩沖區大小。
您不能將指針發送到該結構,因為它在接收過程中沒有任何意義。 由於這兩個進程不共享內存,因此在接收進程中將指向什么?
您需要發送不帶指針的整個結構。 由於您仍然有一個msglen字段,因此您可以使用它來通知接收過程中接下來有多少個字節,並且它可以使用它來讀取一些可變量。 因此,讀取器將讀取長度字段,然后根據長度在第二次讀取時獲得其余消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.