使用命名管道将开关案例值传输到另一个进程

Transfer switch cases value to another process with named pipe

在我的程序中,我想使用命名管道 "pipeselect" 将我的 switch case 值发送到另一个进程。我在管道中写入数字并在另一个程序中读取数字。但是当我 运行 问题时,当我输入一个大小写值时它无法显示任何内容。我该怎么做?

#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);

  }
}

您可能需要像这样使用 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);