Search code examples
cfork

display return value of new program in c using execvp in child process


Working on a uni task where I need to use 1 parent process to create 3 child processes and then perform some calculations on each child process. I am stuck on child 2 where I need to load a program which returns the amount of words in a text file and displays it on the console.

This is my word count file:

wc.c

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

int main( int argc, char *argv[]) {
    char *wordCountFile = argv[1];
    printf("file name passed is %s\n",wordCountFile);
    printf("testing\n");
}

the file above does not actually count the words in a file yet as I am just working on getting it to display in the console

In my main program I have

child2 = fork();
        wordCountFile = argv[1];
        char *cmd = "wc";
        char *args[3];
        argv[0] = "wc";
        argv[1] = wordCountFile;
        argv[2] = NULL;
        if (child2 == 0){
            printf("I am child two my pid is %d \n",getpid());
            printf("I will now execute wc program to count all the words in file %s \n",wordCountFile);
            execvp(cmd, args);
            exit(3);
        }

my output is the following:

I am child two my pid is 659
I will now execute wc program to count all the words in file test.txt

I am trying to get the wc program to print to the console

I have compiled wc.c and the program is in the same directory as my main code.


Solution

  • There are some mistakes in your main program. you are modifying argv and passing args to execvpe and you are calling wc program not ./wc. If you are in unix system you probably have /usr/bin/wc, and execvpe will call that program.

    Correction to your main program

    child2 = fork();
            wordCountFile = argv[1];
            char *cmd = "./wc";
            char *args[3];
            args[0] = "./wc";
            args[1] = wordCountFile;
            args[2] = NULL;
            if (child2 == 0){
                printf("I am child two my pid is %d \n",getpid());
                printf("I will now execute wc program to count all the words in file %s \n",wordCountFile);
                execvp(cmd, args);
                exit(3);
            } 
    

    Now main program will call wc program in current directory.