【发布时间】:2017-08-05 14:57:33
【问题描述】:
我在 Linux 中使用mkfifo 命令。
这是我的代码:
#include <stdio.h>
#include <sys/types.h> // mkfifo
#include <sys/stat.h> // mkfifo
#include <fcntl.h> // O_WRONLY
#include <string.h>
int main(){
char* filename = "myf";
int res = mkfifo(filename, 0777);
pid_t x = fork();
if(x){
char buff[4];
res = open("myf", O_RDONLY);
if(res == -1){
printf("problem opening fifo\n");
}
while(read(res, buff, 4)){
printf("Father: %s\n", buff);
}
}
else{
int toFath = open (filename, O_WRONLY);
char buff [4];
strcpy(buff, "hi");
write(toFath, buff, strlen(buff));
strcpy(buff, "bye");
write(toFath, buff, strlen(buff));
close(toFath);
}
return 0;
}
但它会打印:
Father: hi@
Father: bye
我不明白为什么会有这些我没有写的字符 (@)。我知道strcpy 复制带有空终止符的字符串,所以当父亲打印时它应该在空终止符处停止,为什么不呢?
【问题讨论】:
-
然后试试 strlen+1。