我在Linux中使用mkfifo
命令。 這是我的代碼:爲什麼使用命名管道給C中的隨機字符?
#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: [email protected]
Father: bye
我不明白爲什麼有這些字符,我沒有寫(@)。我知道strcpy
複製與空終止符的字符串,所以當父親打印它應停止在空終止符,爲什麼不是?
然後嘗試strlen + 1。 –