2015-11-17 21 views
0

我已經寫兩個方案中,第一個具有一個開關殼體和創建命名管道「pipeselect」讀出由用戶的值開關和第二個讀出的用命名管道返回值。但不管我輸入1還是2,第二個程序也會顯示「選項1被選中」。我的腳本有什麼問題?由用戶選擇的值發送到其他過程與命名管道

計劃1:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <fcntl.h> 

int main() 
{ 
char pipeselect[] = "/tmp/pipeselect"; 
int bufs[2]; 
int fds; 
int select1; 

/* Pipe Creation */ 
if (access(pipeselect, F_OK) == -1) { 
    fds = mkfifo(pipeselect, 0700); 
    if (fds != 0) { 
    printf("Pipe creation error\n"); 
    exit(1); 
    } 
} 

    printf("1. Option 1\n"); 
    printf("2. Option 2\n"); 
    printf("Please select an option: "); 
    scanf("%d", &select1); 

if (select1 == 1 || select1 == 2) 
{ 
    if ((fds = open(pipeselect, O_WRONLY)) < 0) { 
    printf("Pipe open error\n"); 
    exit(1); 
    } 

    bufs[0] = select1;  // put value entered by user into buffer 
    write(fds, bufs, 1); // write 1 byte from the buffer 
    close(fds); 

    printf("Option %d is selected\n", select1); 
} 
else { 
    printf("Wrong Input!\n"); 
} 

unlink(pipeselect); 
exit(0); 
} 

方案2:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <fcntl.h> 

int main() 

{ 
char pipeselect[] = "/tmp/pipeselect"; 
int bufs[2]; 
int fds; 
int select1; 

    if ((fds = open(pipeselect, O_RDONLY)) < 0) { 
    printf("Pipe open error\n"); 
    exit(1); 
    } 

    select1 = read(fds, bufs, 1); // write 1 byte from the buffer 
    printf("Option %d is selected\n", select1); 
    close(fds); 

exit(0); 
} 

回答

0

這是因爲read()因爲你正在閱讀1返回的字節數successfuly閱讀,你的情況1。猜測如何工作並不是一個好主意,一半的時間你會錯誤的。

你必須做什麼讀庫函數文檔,以瞭解他們應如何使用,比如你忽略的scanf()返回valud。

你應該試試這個,而不是

write(fds, bufs, 1); 

if (write(fds, &select1, sizeof(select1)) != sizeof(select1)) 
    fprintf("error writing to pipe: %d:%s\n", errno, strerror(errno)); 
/* Inlucde <errno.h> and <string.h> for this error message to work */ 

而在其他程序,改變

select1 = read(fds, bufs, 1); 

if (read(fds, &select1, sizeof(select1)) == sizeof(select1)) 
    printf("Option %d is selected\n", select1); 

此外,檢查什麼scanf()返回,而不是假設select1被初始化並使用它,萬一它不是你的程序會調用未定義的行爲。


要小心,若發送這樣的數據時,它不會直接合作的字節順序是不一樣的。在這種情況下,它顯然是好的,但如果它是網絡代碼,這不是一個好的做法,因爲你應該考慮端到端的問題。除此之外,這是可以的。

+0

@JeffSon我剛添加的答案。 –

+0

非常好!最後,我得到了我的預期結果......很高興見到你iharob! –