如何向 execl 创建的后台程序提供输入?

问题描述 投票:0回答:1

我正在Linux上编写C程序。同时我有一个可执行文件A,我需要在我正在编写的C程序中调用A。但要运行 A,我需要按任意键,并且我需要在调用 A 后将一个键传递给我正在编写的程序。

A的大致逻辑如下:

// read some config files

fprintf(stderr, "\n---------Hit Any Key To Start");
getc(stdin);

// the rest of the business

我参考了网上的一些资料,编写代码如下:

pid_t pid = fork();

int fd[2];
int read_end = 0;
int write_end = 1;

if(-1 == pipe(fd)) {
    // error warning
}
if(-1 == pid) {
    // error warning
}else if (0 == pid) {
    close(fd[write_end]);
    dup2(fd[read_end], STDIN_FILENO);

    // I am using execl to execute A. 
    // According to the logs, A executes to where it is waiting for input.
    execl(A ...)
}else {
    close(fd[read_end]);
    char key = 'y';

    // The two inputs are just me worrying that A didn't get the message so I input it a few more 
    // times, but it doesn't work
    write(fd[write_end], &key, sizeof(key));
    sleep(10);
    write(fd[write_end], &key, sizeof(key));

    // I need to terminate A after it executes for a while, so I wrote this code.
    sleep(75);
    kill(pid, SIGTERM);

    // Other things
    // ...
}

我期望发生的是,我用 bash 脚本启动我的程序,然后我的程序调用 A 并让 A 正常运行一段时间,然后退出。

我的母语不是英语,所以如果我的措辞有误,请告诉我。

c pipe fork execl
1个回答
0
投票
pid_t pid = fork();

int fd[2];
int read_end = 0;
int write_end = 1;

if(-1 == pipe(fd)) {

您在 fork 之后创建了管道,因此该管道对于进程来说是本地的。在分叉之前创建它,因此它是共享的。

总体而言,您的整个程序看起来像

timeout 75 bash -c 'yes | "$@"' -- A
并且看起来不需要单独编译的 C 代码。

© www.soinside.com 2019 - 2024. All rights reserved.