Angus
Angus

Reputation: 12621

Path variables and environmental variables

I am trying to get the command through parent and execute it in different process(child process).

#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<malloc.h>

int main(){
 pid_t pid = -1;
 int status = -1;
 char* ip = malloc(20);
 char* a[20];
 int pd[2];
 char* path = NULL;

 path = getenv("PATH");
 printf("\n path : %s \n",path);

 a[0] = malloc(10);

 while(1){
  pipe(pd);
  pid = fork();
  if(pid == 0){
   //printf("\n Child! - pid : %d \n",getpid());
   sleep(1);
   close(pd[1]);
   read(pd[0],ip,20);
   a[0] = ip;
   //execl(ip,ip,NULL);
   execv(path,a);
   exit(0);
  }
  else{
   //printf("\n Parent! - pid : %d \n",getpid());
   printf("(Enter a executable)$  ");
   scanf("%s",ip);
   //printf("\n %s \n",ip);
   close(pd[0]);
   write(pd[1],ip,20);
   waitpid(pid,&status,0);
   //printf("\n The child %d exited with status : %d \n",pid,status);
  }
 }
 free(ip);
 return 0;
}

What is the difference between the path and the environment. The getenv function gives me the whole path of the executable. The above program is not executing the command ls -l.

I want to execute the commands ls -l and the output should display on the screen as well as it should be stored in a file. I tried to do execute the command ls -l. But its not executing. Is there a way to output the ls -l to a file when its outputing on the screen?

Upvotes: 0

Views: 92

Answers (2)

Gavin Smith
Gavin Smith

Reputation: 3154

You run execv(path,a), using path as the first parameter, but you have set path to be the contents of the PATH environment variable. PATH is a list of directories for the shell to search for an executable; the first argument to execv should be the path of the executable to call. (Alternatively, execlp and some other variants can search the `PATH`` environment variable.)

There are some other problems with your code. It looks like the entire of what was typed in is used as the name of the program (e.g. it will look for an executable with the five-character name "ls -l"), and will break for commands longer than about 20 characters.

Upvotes: 0

CS Pei
CS Pei

Reputation: 11047

yes, there is a way to output to the screen and to a file at the same time, it is called tee.

    ls -l | tee your_output_file

Upvotes: 1

Related Questions