I’m writing a program to take user input from the command line (linux/unix commands), and execute them within my program.
My steps so far:
- Ask user for number of commands input
- Fork() to create child process
- Output Child PID and Parent PID
- Allow user to input each command, read each input into an index of argv
- Use execv to run each command inside of argv
The main issue is that when it executes, it merely does the “bin/ls/” in the execv command.
Here is a sample output from running my program:
Enter number of commands: 2
Child’s PID is 3487. Parent’s PID is 3485
Enter a UNIX command: ls
Enter a UNIX command: -al
LIST OF FILES AS IF TYPING “LS” ON THE CMD LINE
Process Complete.
And here is my source code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
void main(int argc, char *argv[20])
{
int pid;
int num = 0;
printf("Enter number of commands: ");
scanf("%d", &argc);
pid = fork();
if(pid == 0)
{
printf("Child's PID is %d. Parent's PID is %d\n", (int)getpid(), (int)getppid());
for(num=0; num < argc; num++)
{
printf("Enter a UNIX command: ");
scanf("%s", argv[num]);
}
argv[num+1] = 0;
execv("bin/ls/", argv);
}
else
{
wait(pid);
printf("Process Complete.\n");
exit(0);
}
}
Firstly you are defining
char* argv[20]inmainwhich is not a good idea. If you ever pass in more than 20 arguments you will exceed the bounds of the array.Secondly, you are attempting to read a string with
scanf("%s", argv[num])into an address space that is not initialized as far as I can tell.The argv[] array of “strings” is initialized by the OS when your program is invoked and if you don’t pass any arguments to your program you will not have any “strings”, meaning that you will be writing to random memory which you might not own.
If you really want to load your commands the way you are doing it now please try the following:
Alternatively you could just pass arguments to your main program which simply passes them onto the called program like so: