我编写了两个程序,第一个程序有一个 switch case 并创建一个命名管道“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);
}
最佳答案
因为read()
返回成功读取的字节数,在您的情况下为 1
,因为您正在读取 1
。猜测事情应该如何运作并不是一个好主意,一半的时间你都会错。
您必须做的是阅读库函数文档以了解应如何使用它们,例如您忽略 scanf()
的返回值.
您应该尝试这个1,而不是
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
已初始化并使用它,以防不是您的程序会调用未定义的行为。
1请注意,如果像这样发送数据时字节顺序不同,则无法直接工作。在这种情况下,显然没问题,但如果它是网络代码,这不是一个好方法,因为您应该考虑字节序。除此之外,这还可以。
关于c - 使用命名管道将用户选择的值发送到其他进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33756522/