2015-11-04 20 views
0

在我的程序中,我希望使用命名管道「pipeselect」將我的開關大小值發送到另一個進程。我在管道中寫入數字並在另一個程序中讀取數字。但是,當我運行該問題時,它不能顯示任何東西,當我輸入案例值。我怎樣才能做到這一點?將開關值轉換到另一個具有命名管道的進程

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

int main() 
{ 
    char pipeselect[] = "/tmp/pipeselect"; 
    char 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); 

    int i = select1; 

    switch (i) 
    { 
    case 1: 
    if ((fds = open(pipeselect, O_WRONLY)) < 0) 
    { 
     printf("Pipe open error\n"); 
     exit(1); 
    } 
    write(fds, bufs, i); 
    close(fds); 

    printf("Option 1 is selected\n"); 
    break; 

    case 2: 
    if ((fds = open(pipeselect, O_WRONLY)) < 0) 
    { 
     printf("Pipe open error\n"); 
     exit(1); 
    } 
    write(fds, bufs, i); 
    close(fds); 

    printf("Option 2 is selected\n"); 
    break; 

    default: 
    printf("Wrong Input!\n"); 
    break; 

    unlink(pipeselect); 
    exit(0); 

    } 
} 
+0

你寫的'i'字節(其中'i'是用戶輸入的)未初始化緩衝區「buf」到管道的選項。這沒有任何意義。你想達到什麼目的? –

+0

我想將用戶輸入值轉移到另一個程序 –

回答

0

您可能需要使用write這樣的:

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

順便說一句,你可以縮小你這樣的代碼:

... 
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); 
+0

謝謝Michael!你是有幫助的...但我已經改變了代碼並再次運行程序...我仍然無法獲得選項1被選中...我不知道爲什麼.. –

+0

@JeffSon如果帖子是有用的你可以放棄它,甚至將它標記爲「答案」。關於你的程序仍然沒有按照你的預期運行,你應該發佈一個新的問題。 –

相關問題