C 将用户选择的值发送到具有命名管道的其他进程

C 将用户选择的值发送到具有命名管道的其他进程,c,switch-statement,named-pipes,C,Switch Statement,Named Pipes,我已经编写了两个程序,第一个程序有一个开关大小写,并创建一个命名管道pipeselect以按用户读取值开关,第二个程序用命名管道读取值。但无论I类型1还是2,第二个程序也会显示选项1。我的脚本有什么问题 方案1: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main() { char pipeselect[] = "/tmp/

我已经编写了两个程序,第一个程序有一个开关大小写,并创建一个命名管道pipeselect以按用户读取值开关,第二个程序用命名管道读取值。但无论I类型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);
}
这是因为返回成功读取的字节数,在您的情况下是1,因为您正在读取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 */

另外,检查scanf返回的内容,而不是假设select1已初始化并使用它,以防您的程序调用未定义的行为


1请小心,如果在发送这样的数据时端点不相同,则无法直接工作。在本例中,这显然是可以的,但如果是netwrok代码,这不是一个好的方法,因为您应该考虑endianness。除此之外,这还可以。

@JeffSon我刚刚在答案中添加了这个。非常好!!最后我得到了我预期的结果…很高兴见到你,伊哈罗布!
select1 = read(fds, bufs, 1);
if (read(fds, &select1, sizeof(select1)) == sizeof(select1))
    printf("Option %d is selected\n", select1);