0

I'm trying to write a program to execute and schedule a list of processes. My code for main.c is below. When run, I receive an error from perror saying there is no such file or directory. I'm guessing this is because the files/programs in my files.txt are not binary executables but I'm not sure how to fix this. files.txt contains the list of programs I want to run. They have all been converted to binary executables already. programs is an array containing the four programs that have been read by the readPrograms function

int main(int argc, char ** argv) {
    pid_t pid[50];
    pid_t wpid;
    int i, j;
    int status = 0;
    char *newenvp[] = {NULL};
    char *newargv[] = {"./files.txt", NULL};

    printf("Before forking in the parent\n");
    int numProgs = readPrograms();

    for (i=0; i<numProgs; i++) {
        pid[i] = fork();
        if (pid[i] < 0) {
            perror("fork error");
            exit(EXIT_FAILURE);
        }
        else if (pid[i] == 0) {
            printf("Child process running\n");
            execve(programs[i], newargv, newenvp);
            perror("execve error");
            exit(EXIT_FAILURE);
        }
    }
    for (i=0; i<numProgs; i++) {
        wait(&status);
    }
    return 0;
}
char* programs[50];
int readPrograms();

files.txt below

./first
./second
./third
./fourth

(I did "cc first.c -o first" for all of these files respectively)

user3192682
  • 123
  • 1
  • 2
  • 11
  • Use `strace -f -e execve` to look at the actual syscalls being made. If the error is what @R suspects, it'll be plain to see. (If that isn't illuminating, I'd take off the `-e execve` filter and take a more general look for a syscall returning ENOENT). – Charles Duffy Oct 29 '14 at 02:55
  • ...by the way, it would be more conventional to pass your target file as `argv[1]`, not `argv[0]`; unless one has a specific reason for it to be otherwise, `argv[0]` is by convention the name of the program being run. – Charles Duffy Oct 29 '14 at 02:58
  • the parameter newargv[] is not being correctly set. it should contain newargv[0] = programs[i]; newargv[1] = NULL; – user3629249 Oct 29 '14 at 17:22
  • @user3629249 It was working as I wanted it to with R's fix. When I tried this way, (which I'm sure is correct) I got a segfault. Not sure how to fix this unfortunately... – user3192682 Oct 30 '14 at 03:21

1 Answers1

1

I suspect the bug is in the code you're not showing, readPrograms. Most likely you're reading the lines of the text file with fgets and each string has a newline on the end of it, whereas your filenames don't have newlines in them.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711