Search code examples
clinuxbashpopen

timeout command does not work with popen and output redirection


I am using ssh to run a command on a remote host whose output I redirect to a file on my local host. I now need to use a timeout, but unable to use it for the command. The command is not getting executed, but instead the command is waiting for the timeout time (15 seconds). When I manually try this command on bash, it works. But, it does not work on popen (has that got to do anything with "sh -c cmd" ?).

    cmd = "timeout 15s sudo ip netns exec some_namespace ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o Loglevel=error admin@192.168.2.35 'remote_cmd remote_cmd_arg' > local_filename";

    if((pipe = popen(cmd, "r")) == NULL)
    {
        printf(stderr, "Error opening pipe\n");
        return -1;
    }

Solution

  • Copied OP answer from the comments:

    I found a way to get it work. I used "timeout --foreground 15s" instead and it works now. This allows the ssh command to interact with the terminal. I believe it otherwise would be a background process and may have been paused as soon as it wrote its ssh prompt to its stdout. Thank you for helping me out @thatotherguy