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);
}
@JeffSon我剛添加的答案。 –
非常好!最後,我得到了我的預期結果......很高興見到你iharob! –