While I think I have the grasp on how fork(), exec(), wait() and pid work in C, I have yet to find a way how to run a personal program from within a program.
Here's my code:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h> /* for fork() */
#include<sys/types.h> /* for pid_t */
#include<sys/wait.h> /* fpr wait() */
int main(int argc, char* argv[])
{
char fileName[255];
pid_t pid;
switch (pid = fork()) {
case -1: //Did not fork properly
perror("fork");
break;
case 0: //child
execv(fileName[0],fileName);
puts("Oh my. If this prints, execv() must have failed");
exit(EXIT_FAILURE);
break;
default: //parent
//Infinite Loop
while (1) {
printf(" %s > ", argv[0]);
scanf("%s", fileName); // gets filename
if (fileName[0] == '\0') continue;
printf("\n Entered file: %s",fileName); // prints the fileName
waitpid(pid,0,0); /* wait for child to exit() */
break;
}
}
return 0;
}
My questions are the following:
I want to take a string as an input and I want to limit its scope to 255 characters. Is
char fileName[255]and thenscanf("%s", fileName);the way to go? Should I usegetLine()or some other function instead?Let's say that the input is taken correctly. How do I execute say an existing hello world program. Will the input be stored in
*argv[]? I found out that in a different program I could usestatic char *argv[] = { "echo", "Foo is my name." , NULL }; execv("/bin/echo", argv);in order to echo "Foo is my name.". Can I do something similar with a helloWorld program?