2017-08-05 45 views
-2

我在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複製與空終止符的字符串,所以當父親打印它應停止在空終止符,爲什麼不是?

+3

然後嘗試strlen + 1。 –

回答

1

的strlen(淺黃色)返回圖3,因此寫()將輸出不被初始化的buff

+0

考慮編寫這個答案來解釋*爲什麼*'strlen(buff)'返回3. –

+0

編號給定'strcpy(buff,「hi」);','strlen(buff)'返回2,而不是3。 –

0

第一char buff[4]的前3個字節。結果,read(res, buff, 4)可能會返回一個不是'\ 0'終止的buff。

一個修復,初始化第一個buff用這個char buff[4] = {0}