简体   繁体   English

使用命名管道将命令发送到正在运行的进程

[英]Sending a command to a running process using a named pipe

I have a program that runs as a service, which takes the standard input from the console, and prints the feedback to the screen. 我有一个作为服务运行的程序,该程序从控制台获取标准输入,并将反馈打印到屏幕上。 It can be thought as the following simple example, while the printf() function is actually some more complicated function. 可以将其视为以下简单示例,而printf()函数实际上是一些更复杂的函数。

//keyin.c
int main(int argc, char *argv[])
{
    char buf[80];
    int i = 1;

    while(i++){ 
    printf("enter %d string: \n", i);
    scanf("%s", buf);
    printf("print %d string: %s \n\n", i, buf);
    sleep(2);
    }

    return 0;
}

Now I want to use a named pipe as the input so that I can use another program to pass desired commands to the service by writing to the pipe, instead of typing in the console. 现在,我想使用命名管道作为输入,以便可以使用另一个程序通过写入管道将所需命令传递给服务,而不是在控制台中键入。

I created a named pipe by: 我通过以下方式创建了一个命名管道:

mknod MYFIFO p

and then I redirect the input by: 然后通过以下方式重定向输入:

root@ubuntu: ./keyin < MYFIFO

and then I write the command into pipe by: 然后通过以下命令将命令写入管道:

root@ubuntu: echo "test" > MYFIFO

I expect the service take the "test", print it out, and wait for the next input, however, after the first run, it keeps printing out "test" infinitely, and never responds to the pipe file again, even when I delete it. 我希望该服务接受“测试”,将其打印出来,然后等待下一次输入,但是,在第一次运行后,它会无限期地打印出“测试”,并且即使我删除了它也永远不会再响应管道文件它。

What did I do wrong? 我做错了什么?

You should check the return value of scanf() . 您应该检查scanf()的返回值。 Note that for every time you get the same repeated buffer, scanf() would return a negative value. 请注意,每次获得相同的重复缓冲区时, scanf()都会返回负值。

int main(int argc, char *argv[]){
   char buf[80];
   int i = 1;
       while(i++){
       if(scanf("%s", buf) > 0){
           printf("print %d string: %s \n\n", i, buf);
       }
       sleep(2);
    }
    return 0;
}

Also, note that a named pipe is not like a normal pipe or the console and will behave differently. 另外,还要注意命名管道是不是一个普通的管道或控制台,并表现不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM