gpt4 book ai didi

c++ - Linux 中如何与进程通信?

转载 作者:太空宇宙 更新时间:2023-11-04 09:37:16 25 4
gpt4 key购买 nike

大约 5 年前,我有一个完全正确且有效的程序。那时我停止使用它,我升级了操作系统,时间过去了,代码蒙上了灰尘,最后我把它挖出来,发现它不再与子进程通信。

这是代码(经过简化,但它显示了问题所在):

#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <string.h>
#include <sys/time.h>
#include <sys/stat.h>

#include <iostream>
#include <string>
#include <cassert>

int main()
{
std::cout << "Creating the pipe for reading from the process" << std::endl;
const std::string pipe_name = "/tmp/proc_comm";
{
int res = mkfifo(pipe_name.c_str(),0777);
assert(res==0);
}

std::cout << "Launching subprocess" << std::endl;
FILE *cmd_handle = popen(("espeak -x -q -z 1> "+pipe_name+" 2> /dev/null").c_str(), "w");
assert(cmd_handle!=0);

std::cout << "Opening the pipe" << std::endl;
int pipe_id = open(pipe_name.c_str(),O_RDONLY);
assert(pipe_id!=-1);

const std::string message = "hello\n";

std::cout << "Sending the message" << std::endl;
if (!fwrite(message.c_str(),sizeof(char),message.length(),cmd_handle))
assert(0);
if (ferror(cmd_handle))
assert(0);
if (fflush(cmd_handle)!=0)
assert(0);

fd_set output_set;
FD_ZERO(&output_set);
FD_SET(pipe_id,&output_set);

static timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;

std::cout << "Selecting the pipe for reading" << std::endl;
const int inputs = select(pipe_id+1, // max of pipe ids + 1
&output_set,0,0,&timeout);

if (inputs==-1) // error
assert(0);
else if (inputs==0) // nothing to read
assert(0); // HERE (*)
else
{
// we can only read from our pipe
assert(inputs==1);
assert(FD_ISSET(pipe_id,&output_set));

const int bufsize = 20000;
char char_buf[bufsize];
memset(char_buf,0,sizeof(char_buf));

std::cout << "Reading from the pipe" << std::endl;
const int count = read(pipe_id,char_buf,bufsize-1);

if (count==-1)
assert(0);

std::cout << "Read " << count << std::endl;
}

return 0;
}

它编译,运行,创建并打开用于从进程读取的管道,启动子进程,发送消息但没有可从进程读取的内容(行 HERE (*))。

那么现在你是如何从流程中读取数据的?如果可能的话,我想保留一般的工作流程,即使用管道进行读取,使用流程句柄写入流程。

最佳答案

可能在 select() 返回时 FIFO 是空的。

这个简单的实验证明了这一点。

  • 使用修改后的行运行您的代码
    FILE *cmd_handle = popen (("echo begin; espeak -x -q -z 1>" + pipe_name + " 2>/dev/null; echo end;").c_str (), "w"); .
  • cat < /tmp/proc_commn &; ./a.out;
  • 输出为:

    创建用于从进程读取的管道
    启动子进程
    打开管道
    开始
    发送消息
    选择要读取的管道
    a.out: main.cpp:64: int main(): 断言“0”失败。
    h@l'oU #### <--- FIFO 中的数据仅在断言后。
    结束

使用 pclose()。

加上 pclose()调用,问题消失:

if (!fwrite(message.c_str(),sizeof(char),message.length(),cmd_handle))
assert(0);
if (ferror(cmd_handle))
assert(0);
if (fflush(cmd_handle)!=0)
assert(0);

/* pclose added. */
if (pclose (cmd_hanlde) < 0)
{
/* handle error. */
}

fd_set output_set;

那么你现在是如何从流程中读取数据的呢?

我不认为您的代码在任何意义上都已过时。我不是专家,所以我对这个问题没有很好的答案。但我希望这篇文章能帮助您解决问题。

更新。

使用 strace 和 espeak 1.46.2 进行调试。

使用 strace ( strace -f ./a.out ) 和任何 select() 运行您的代码超时:
Porcess 31985是父进程(主进程)。
进程 31987 是子进程 ( espeak )。

# Child process starts trying to read from stdin.
[pid 31987] read(0, <unfinished ...>
[pid 31985] <... sync resumed> ) = 0
[pid 31985] write(1, "Sending the message\n", ...
[pid 31985] fstat64(4, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0
[pid 31985] mmap2(NULL, 4096, PROT_READ|PROT_WRITE, ...

# Main process writes message to the pipe.
[pid 31985] write(4, "hello\n", 6) = 6

# Child process reads message from the pipe.
[pid 31987] <... read resumed> "hello\n", 4096) = 6
[pid 31985] write(1, "Selecting the pipe for reading:3"..., 3 ...
) = 33
[pid 31987] fstat64(1, <unfinished ...>

# Main process calls select().
[pid 31985] select(4, [3], NULL, NULL, {10, 0} <unfinished ...>
[pid 31987] <... fstat64 resumed> {st_mode=S_IFIFO|0755, st_size=0, ...}) = 0
[pid 31987] mmap2(NULL, 4096, PROT_READ ...

# Child process calls read() again (second time).
# Seems like it waits another portion of input.
# Note: The previous input don't processed yet.
[pid 31987] read(0, <unfinished ...>

# Despite big value of `select()` timeout, there is no data processing here.
# Select returns by timeout.
[pid 31985] <... select resumed> ) = 0 (Timeout)
[pid 31985] write(2, "a.out: main.cpp:69: i ...
) = 54
[pid 31985] rt_sigprocmask(SIG_UNBLOCK, [ABRT], NULL, 8) = 0
[pid 31985] gettid() = 31985
[pid 31985] tgkill(31985, 31985, SIGABRT) = 0
[pid 31985] --- SIGABRT (Aborted) @ 0 (0) ---

为什么strace日志中没有输入处理?

让我们看看source codeespeak .这是从 stdin 读取输入的代码(src/espeak.cpp)(假设找出命令行参数在一组内部变量上的映射的正确性):

 728     // line by line input on stdin
729 while(fgets(p_text,max,stdin) != NULL) // <--- * here first and second
730 { // <--- * read() call.
731 p_text[max-1] = 0;
732 espeak_Synth(p_text,max,0,POS_CHARACTER,0,synth_flags,NULL,NULL);
733
734 }

关于espeak_Synth()的评论函数 (src/speak_lib.h:268):

 /*
* Synthesize speech for the specified text.
* The speech sound data is passed to the calling
* program in buffers by means of the callback function specified by
* espeak_SetSynthCallback(). The command is asynchronous:
* it is internally buffered and returns as soon as possible.
* ...
*/

espeak_Synth()是异步函数(这就是为什么我们连续看到两个 read() 调用)。我假设调用 espeak_Synth() , 应该导致数据写入 stdout (经过一些延迟)。但即使 select() 的值(value)很大,它也不会发生。暂停。这里有些奇怪。

关于c++ - Linux 中如何与进程通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25228249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com