0

pretty new to Linux and im trying to read in command line arguments in a Linux operating system. I want to be able to execute the commands i give as command line arguments programatically. Here is what I have so far:

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

int main(int argc, char* argv[])
{
    int counter;
    
    for(counter = 1; counter < argc; counter++){
        
        pid_t pid = fork();
        if(pid < 0)
        {
            perror("Forking failed");
            exit(1);
        }
        else if(pid == 0)
        {
            char *args[] = {argv[counter], NULL};
            printf("Argument to be passed: %s \n", argv[counter]);
            execvp(args[0], args);
            perror("Command failed.");
            exit(0);
        }

        printf("Process %s completed successfully.\n", argv[counter]);
    }
    exit(0);
    
}

My output on terminal:

darren@darren-VirtualBox:~/Desktop$ ./cmdarguments /home/darren/Desktop/fullpathdoc1 /home/darren/Desktop/fullpathdoc2
Process /home/darren/Desktop/fullpathdoc1 completed successfully.
Process /home/darren/Desktop/fullpathdoc2 completed successfully.
darren@darren-VirtualBox:~/Desktop$ Argument to be passed: /home/darren/Desktop/fullpathdoc2 
This is the second program that simply prints this statement. 
Argument to be passed: /home/darren/Desktop/fullpathdoc1 
This is the first program that simply prints this statement.

I want to be able to print out the process name, and say process completed after each command line argument has been successfully executed. For some reason, my output results in everything seeming to execute backwards, with my process completed messages coming up first as well as reading in the command lines from right to left. Can someone please help with my code and how I can rectify this?

thedafferg
  • 99
  • 7

2 Answers2

0

When there are multiple processes, which process get to run first is totally up to your operating system(Linux)'s decision.

xwz7611
  • 138
  • 8
0

Broadly, the parent process -- that's where fork() returns > 0 -- needs to wait for the child process to complete. Bear in mind that the three calls to execvp() result in three, concurrent, processes. So if you don't monitor them, they'll proceed in their own merry way. There is already a discussion of this issue on SO:

how to correctly use fork, exec, wait

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15