我正在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正常运行一段时间,然后退出.
我不是以英语为母语的人,如果我的措辞有误,请告诉我.