0

In Linux i am trying to create a C program that forks and create 2 childs (Child1 and Child2). Each child is performing a process which is to execute the file using execv command. This is a parent file that creates two files destination1.txt and destination2.txt. The codes for these files are inside Prcs_P1.c and Prcs_P2.c. They are the C files. The code compiles and runs but does not perform the operation of executing file. What am i doing wrong? What is the part i am missing?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

int main(int argc, char *argv[])
{
pid child1, child2;
enter code here
child1 = fork();
errno = 0;

if (child1 < 0)
{
    printf("Error! Forking can't be done\n");
}

else if (child1 == 0)
{
    printf("Child one process activated! %d\n", getpid());
    execv("Prcs_P1.c", NULL);
}

else
{
    printf("Parent1 process activated! %d\n", getpid());
}

child2 = fork();

if (child2 < 0)
{
    printf("Error! Forking can't be done\n");
}

else if (child2 == 0)
{
    printf("Child two process activated! %d\n", getpid());
    execv("Prcs_P2.c",NULL);
}

else
{
    printf("Parent2 process activated! %d\n", getpid());
}

return 0;

}

The output is Parent1 process activated! 2614 Parent2 process activated! 2614 Child one process activated! 2615 Parent2 process activated! 2615 Child two process activated! 2617 Child two process activated! 2616

2 Answers 2

2

You should not pass ".c" file as input. It is not executable. You have to pass the executable as input. something like "xxxxxx.out".

Sign up to request clarification or add additional context in comments.

1 Comment

I am in learning stage. I didn't realized that. Thank you it worked
2

As pointed out by Pavan in the other answer, you are passing a non executable file as argument for the execv. Your intention is to execute the C program, shouldn't you be giving the binary compiled out of that C program? Compile your C program that you want the child processes should execute, name them appropriately and input to execv

You should catch the return value of execv to find what happened with it. In your case, it would have returned error - "Exec Format Error".

if( execv("Prcs_P2.c",NULL) < 1)
      printf("execv failed with error %d\n",errno);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.