I would like to use fork from my main program to make a process instance of other program I wrote. Here is example of what I am trying to do:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
int main(int argc, char *argv[]){
char *ar[] = {"./myfile",NULL};
switch (fork()) {
case -1:
printf("Problem.\n");
break;
case 0:
printf("Everything ok...\n");
execv("./myfile",ar);
printf("err\n");
exit(1);
default:
sleep(1);
}
return 0;
}
This is my main program. Program myfile looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <signal.h>
#include <unistd.h>
int main(int argc, char *argv[]){
printf("Hi!\n");
return 0;
}
This is output I am expecting:
Everything ok...
Hi!
But I am only getting:
Everything ok...
What I am doing wrong? execv takes two parameters, but the second one in my case is empty (or NULL?). I tried to add line
char *argv[] = NULL;
to my main program, but I got error because I can't do that in C.
execv
takes two arguments, and the second one, according to the man page, needs to be:
an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a null pointer.
So you should have something like:
char *argv_for_program[] = { filename, NULL };
execv(filename, argv_for_program);
Some other notes:
Your printf
immediately preceding the execv
doesn't end in a newline. Since stdout
is typically line buffered, the text "Everything ok..."
will not be printed until the buffer is flushed. And the execv
replaces your program with ./myfile
, without flushing buffers, so the "Everything ok..."
message is lost. To fix this, print "Everything ok...\n"
instead, or call fflush(stdout)
before execv
.
execv
only returns if you failed to execute the program. In this case, it's probably not desirable to exit(EXIT_SUCCESS)
; it'd be better to print an appropriate error message (e.g. with perror
) and exit with a failure code.
As noted in comments, you need to #include <unistd.h>
.