Search code examples
clinuxinputio

Data transfer to a child process through the pipe() syscall: how to imitate pressing enter (during the input) in terminal?


There is a program that reads a login and a password gradually. My program invokes this one and redirect her input through the pipe() syscall. It works like this:

int main(void)
{
    int pipes[2];
    pipe(pipes);
    pid_t pid = fork();
    if (!pid)
    {
        close(pipes[1]); // close write-descriptor
        dup2(pipes[0], 0); // copy read-descriptor to 0, hence replace standard input with our pipe descriptor.
        execl(...);
    }
    else if (pid > 0)
    {
        close(pipes[0]);
        ...
        write(pipes[1], "username\n", 9); // transfer username (here is a problem)
        write(pipes[1], "password\n", 9); // transfer password (and here is one)
    }
    else
    { ... }
    return 0;
}

Both the login and the password have read in login variable in the invoked program. I assume the invoked program is reading like this:

read(0, buff_login. 1024);
...
read(0, buff_password, 1024);
...

If we run this program in a terminal and press enter button after the login is entered, in the invoked program the read() syscall returns control of the program and writes in a buffer all that passed as input.. and then it calls the second read() for reading a password.

How can i imitate this behavior from the my program with pipes descriptors? Because if i write the '\n' char to the pipe descriptor it has no affect on the read() syscall in the invoked program and it continues to read in a buffer of a login.


Solution

  • If someone is interested how i fix this: solution is put the sleep(1) between the two calls of write().