Search code examples
cshellubuntuexecpopen

Ubuntu C code how to execute command in another folder


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
    char *buffer = malloc(1024);
    FILE* f = popen("ls", "r");
    int byteReads = fread(buffer, 1, 1024, f);
    fclose(f);
    printf("%s\n", buffer);

    return 0;
}

Ther are 2 folders ./parent/folder1 and ./parent/folder2 . ./main is in folder1, and I want it to execute ls in folder2 and get the result.

Not something that is specific to "ls", but that works for any commands in general.

How can I do it using popen()? Or do I have to use another command?


Solution

  • You could use popen as you use it in your question. You could pass the cmd you want to execute as argument to the program call, e.g. if your program is named myexecute the command line call would look like this:

    myexecute folder2 'ls -l' 
    

    or

    myexecute 'another folder' 'ls' 
    

    Please note the single quotes to get an argument if spaces are included in the argument.

    With chdir you can change the current working directory. The output of the command can be read in a loop and output to the stdout. Finally, with pclose, you would wait for the associated process to finish and it would even return the exit status of the executed command, just in case you are interested.

    You code slightly modified could look like this:

    #include <stdio.h>
    #include <stdlib.h>
    #include <libgen.h>
    #include <unistd.h>
    
    int main(int argc, char *argv[]) {
        if(argc != 3) {
            fprintf(stderr, "usage: %s '<dir>' '<cmd>'\n", basename(argv[0]));
            return EXIT_FAILURE;
        }
        if(chdir(argv[1]) != 0) {
            perror(argv[1]);
            return EXIT_FAILURE;
        }
        FILE *f = popen(argv[2], "r");
        if (!f) {
            perror("popen failed");
            return EXIT_FAILURE;
        }
        char buf[1024];
        while (fgets(buf, sizeof(buf), f)) {
            printf("%s", buf);
        }
        if (pclose(f) != 0) {
            perror("pclose failed");
        }
        return EXIT_SUCCESS;
    }