我正在运行我在Oracle网站上找到的全双工服务器/客户端代码:
写作./fd_client哈哈哈时我会得到类似的东西:
HAHAHA0 $0
大写是好的(它应该是它应该返回的服务器)但是,我该怎么回避垃圾?
fd_client.c
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */
int main(int argc, char *argv[])
{
int wrfd, rdfd, numread;
char rdbuf[MAX_BUF_SIZE];
/* Check if an argument was specified. */
if (argc != 2) {
printf("Usage : %s \n", argv[0]);
exit (0);
}
/* Open the first named pipe for writing */
wrfd = open(NP1, O_WRONLY);
/* Open the second named pipe for reading */
rdfd = open(NP2, O_RDONLY);
/* Write to the pipe */
write(wrfd, argv[1], strlen(argv[1]));
/* Read from the pipe */
numread = read(rdfd, rdbuf, MAX_BUF_SIZE);
rdbuf[numread] = '0';
printf("Full Duplex Client : Read From the Pipe : %s\n", rdbuf);
return 0;
}
fd_server.c
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */
int main(int argc, char *argv[])
{
int rdfd, wrfd, ret_val, count, numread;
char buf[MAX_BUF_SIZE];
/* Create the first named - pipe */
ret_val = mkfifo(NP1, 0666);
if ((ret_val == -1) && (errno != EEXIST)) {
perror("Error creating the named pipe");
exit (0);
}
ret_val = mkfifo(NP2, 0666);
if ((ret_val == -1) && (errno != EEXIST)) {
perror("Error creating the named pipe");
exit (0);
}
/* Open the first named pipe for reading */
rdfd = open(NP1, O_RDONLY);
/* Open the second named pipe for writing */
wrfd = open(NP2, O_WRONLY);
/* Read from the first pipe */
numread = read(rdfd, buf, MAX_BUF_SIZE);
buf[numread] = '0';
printf("Full Duplex Server : Read From the pipe : %s \n", buf);
/* Convert to the string to upper case */
count = 0;
while (count < numread) {
buf[count] = toupper(buf[count]);
count++;
}
/*
* Write the converted string back to the second
* pipe
*/
write(wrfd, buf, strlen(buf));
}
fullduplex.h
#define NP1 "/tmp/np1"
#define NP2 "/tmp/np2"
#define MAX_BUF_SIZE 255
答案 0 :(得分:2)
你的意思是:
rdbuf[numread] = '\0';
fd_server.c中的buf也存在同样的问题。
答案 1 :(得分:2)
此:
buf[numread] = '0';
错了。你想要:
buf[numread] = '\0';
(与rdbuf[numread] = '0';
相同。)
答案 2 :(得分:-1)
这些行产生错误输出:
buf[numread] = '0';
printf("Full Duplex Server : Read From the pipe : %s \n", buf);
首先,buf[numread] = '0';
覆盖你的空终止符
如果被覆盖,printf(%s)
不知道在哪里停止打印。
null-terminator告诉C字符串结束的位置 在你覆盖它之后,C不再知道字符串结尾的位置,并打印你的字符串“HAHAHA”,但之后会继续打印垃圾。