Shaco icon indicating copy to clipboard operation
Shaco copied to clipboard

feature request

Open rhakb opened this issue 2 years ago • 3 comments

hi, bro Can you obtain command output through pipelines? This can avoid blocking long running commands

rhakb avatar May 06 '23 23:05 rhakb

yeah, of course, but pipelines still going block, an alternative is creating threads for commands.

If you have something as an example, I'll reproduce.

Or did I get it wrong? show me your idea bro

thanks for contributing!

souzomain avatar May 07 '23 01:05 souzomain

Let's implement this.

but for extented commands, demon of havoc uses job command, I can create this.

do you think best implement this for all commands executed or create "job" command to this?

souzomain avatar May 07 '23 18:05 souzomain

Sorry, I have removed the fork function and improved the program. Here is the code

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#define BUFFER_SIZE 1024

int main(int argc, char *argv[]) {
    char buffer[BUFFER_SIZE];
    FILE *nmap_pipe;
    int fd;
    fd_set set;
    struct timeval timeout;

    // Execute the nmap command and open the pipeline
    nmap_pipe = popen("ping 192.168.0.1", "r");
    if (!nmap_pipe) {
        fprintf(stderr, "Failed to open pipe: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    // Set the pipeline to non blocking mode
    fd = fileno(nmap_pipe);
    fcntl(fd, F_SETFL, O_NONBLOCK);

    //Background operation loop
    while (1) {
        //Use the select function to read the pipeline without blocking
        FD_ZERO(&set);
        FD_SET(fd, &set);
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;
        int result = select(fd + 1, &set, NULL, NULL, &timeout);
        if (result == -1) {
            fprintf(stderr, "Failed to select pipe: %s\n", strerror(errno));
            exit(EXIT_FAILURE);
        } else if (result == 0) {
            // Pipeline has no data, continue with background operation
            printf("No data in pipe, continue.\n");
            sleep(1);
            printf("Continue other work...\n");
        } else {
            // There is data in the pipeline, output and continue with background operations
            ssize_t len = fread(buffer, 1, BUFFER_SIZE - 1, nmap_pipe);
            if (len == -1) {
                fprintf(stderr, "Failed to read pipe: %s\n", strerror(errno));
                exit(EXIT_FAILURE);
            } else if (len == 0) {
                // The pipeline has been closed
                printf("Pipe closed.\n");
                break;
            } else {
                buffer[len] = '\0';
                printf("Data in pipe: %s\n", buffer);
                sleep(1);
                printf("Continue other work...\n");
            }
        }
    }

    // Close pipeline
    pclose(nmap_pipe);

    return 0;
}

rhakb avatar May 08 '23 02:05 rhakb