By thedafferg

2020-09-16 05:13:39 8 Comments

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");
        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.");

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

My output on terminal:

[email protected]:~/Desktop$ ./cmdarguments /home/darren/Desktop/fullpathdoc1 /home/darren/Desktop/fullpathdoc2
Process /home/darren/Desktop/fullpathdoc1 completed successfully.
Process /home/darren/Desktop/fullpathdoc2 completed successfully.
[email protected]:~/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?


@Kevin Boone 2020-09-16 06:59:15

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

@xwz7611 2020-09-16 05:27:13

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

Related Questions

Sponsored Content

Sponsored Content