Search code examples
cpipeforkexecl

How do I provide input to a background program created by execl?


I am writing a C program on Linux. At the same time I have an executable file A. I need to call A in the C program I am writing. but to run A I need to press any key, and I need to pass a key to the program I am writing after it calls A.

The approximate logic of A is as follows:

// read some config files

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

// the rest of the business

I refer to some information on the Internet and write the code as follows:

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
    // ...
}

What I expect to happen is that I am starting my program with a bash script, then my program calls A and lets A run normally for a while and then exits.

I am not a native English speaker, so please let me know if my wording is wrong.


Solution

  • pid_t pid = fork();
    
    int fd[2];
    int read_end = 0;
    int write_end = 1;
    
    if(-1 == pipe(fd)) {
    

    You created the pipe after fork, so the pipe is local to the process. Create it before forking, so it is shared.

    Overall, your whole program looks like timeout 75 bash -c 'yes | "$@"' -- A and doesn't look like requires a separate compiled C code.