Search code examples
cfileforkexecvp

How to use execvp or any of the other exec's to run on only one file?


I want to execute execvp, or really any of them that would work for this, but only run it on the file given. To explain what I am trying to do, I am trying to run it on files that meet the other arguments given. Ex: (./a.out -s 1024 -e "ls -l") -s being if the file size is >= 1024 then show that file and then excute the command "ls -l" on that file. My code checks every file in the directory and only shows the ones that pass. I am having trouble understanding how I would just show that one file and not all the files in the directory.

if (flagArgs.e_flag) // e case
{
    char *cmd = "ls";
    char *argv[3];
    argv[0] = "ls";
    argv[1] = "-la";
    argv[2] = NULL;
    printf("DIRFILE: %s\n", dirfile);

    if (strcmp(line, "") != 0){
        if ((pid = fork()) < 0) {     /* fork a child process           */
            printf("*** ERROR: forking child process failed\n");
            exit(1);
        }
        else if (pid == 0) {          /* for the child process:         */
            if (execvp(dirfile, argv) < 0) {     /* execute the command  */
                printf("*** ERROR: exec failed\n");
                exit(1);
            }
        }
        else {                                  /* for the parent:      */
            while (wait(&status) != pid)       /* wait for completion  */
                ;
        }
    }

}

I understand that i am using execvp wrong in this code as i should be passing (cmd, argv) but I am trying to figure out how i can just run the given command on one singular file. Is there any way i can do this or is using execvp wrong?

Thanks for any help!


Solution

  • Add the filename to the argv array. The first argument to execvp() should be the program to run, which is usually the same as argv[0].

    if (flagArgs.e_flag) // e case
    {
        char *cmd = "ls";
        char *argv[4];
        argv[0] = "ls";
        argv[1] = "-la";
        argv[2] = dirfile;
        argv[3] = NULL;
        printf("DIRFILE: %s\n", dirfile);
    
        if (strcmp(line, "") != 0){
            if ((pid = fork()) < 0) {     /* fork a child process           */
                printf("*** ERROR: forking child process failed\n");
                exit(1);
            }
            else if (pid == 0) {          /* for the child process:         */
                if (execvp(argv[0], argv) < 0) {     /* execute the command  */
                    printf("*** ERROR: exec failed\n");
                    exit(1);
                }
            }
            else {                                  /* for the parent:      */
                while (wait(&status) != pid)       /* wait for completion  */
                    ;
            }
        }
    }