I'm trying to run two executables consecutively using this c code:
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
fork();
execv("./prcs1", &argv[1]); // GIVE ADDRESS OF 2nd element as starting point to skip source.txt
fork();
execv("./prcs2", argv);
printf("EXECV Failed\n");
}
The program exits after the first execv() call despite the fork, it never gets to the second execv(). I've tried calling wait() after the first fork but I'm not sure that's what it's missing.
Any ideas why control doesn't return to the parent after the child exits?
You haven't had much reading on fork() I guess.
when you call
fork()
, it creates a child process which will run the same code from fork.fork()
returns three kind of valuesyour code should look like this.
You need to understand how fork and execv work together.
You need stdlib for exit (in case execv fails), and errno, to print the reason,
You may want to examine the reason your child exited (core dump, signal, normal exit), thus I have added this function,
And here is your program annotated with comments explaining which sections of code are processed by the parent, and which by the child(ren).
The exec family will only return if the call fails.
Since you do not check the return value of fork you will call execv in parent and child process.
Check the return value: if it is 0 you are in the child process, if it is bigger than zero you are in the parent process. Below zero means the fork failed.
You have a couple of problems. First, if you only want to run two programs, you only need to call
fork()
once. Then run one program in the parent process and one in the child. Second, you're constructing theargv
array to be passed toexecv
incorrectly. The first entry should be the executable name. Do something like:Note that this example does no error checking.