我正在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正常运行一段时间,然后退出.

我不是以英语为母语的人,如果我的措辞有误,请告诉我.

推荐答案

pid_t pid = fork();

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

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

您在fork之后创建了管道,因此该管道对于进程来说是本地的.在Forking 之前创建它,这样它就是共享的.

总体而言,您的整个程序看起来像timeout 75 bash -c 'yes | "$@"' -- A个,并且看起来不需要单独编译的C代码.

C++相关问答推荐

使用额外的公共参数自定义printf

GCC预处理宏和#杂注GCC展开

使用sscanf获取零个或多个长度的字符串

判断X宏的空性

如何用c语言修改shadow文件hash部分(编程)?

将返回的char*设置为S在函数中定义的字符串文字可能会产生什么问题?

#定义SSL_CONNECTION_NO_CONST

为什么用非常数指针变量改变常量静态变量时会出现分段错误?

GCC奇怪的行为,有fork 和印花,有换行符和不换行符

在vfork()之后,链接器如何在不 destruct 父内存的情况下解析execve()?

我在反转双向链表时遇到问题

C整型和_泛型.哪些类型是兼容的?

Fprintf正在写入多个 struct 成员,并且数据过剩

我不知道为什么它不能正常工作,我用了get()和fget(),结果是一样的

Valgrind正在使用一个Fexecve电话报告不可能发生的事情

如何打印循环调度问题的时间表

Leet代码运行时错误:代码不会在Leet代码上编译,而是在其他编译器中编译,如netbeans和在线编译器

为什么 Linux 共享库 .so 在内存中可能比在磁盘上大?

段错误try 访问静态字符串,但仅有时取决于构建环境

strided memcpy(3) 在 libvpx 中如何工作