I am trying to implement some kind of a which program. I could get the PATH environment variable and was able to tokenize it. I have a list of paths in tokens[]. Now, I have the name of the shell command. How would I search the tokens[] and display where the command was found?
Thank You. One problem I'm facing is that it is giving me a segmentation fault.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include "extern.h"
char* program_name;
int allpaths; /* -a */
int readalias; /* -r */
const char *name = "PATH";
char *value;
int result;
char *filename;
char *pathsep = "/";
int i;
/*PASTED ONLY THE REQUIRED PART*/
int processIt(const char* command, char* paths[])
{
/* check your arguments! */
/* At this point, the command line options have been taken care of assuming that only one option was there.
Now, we need to take this "command" that was sent to us from the main function and then search for this command in the paths.*/
/*paths contains the current path to be searched*/
for(i=0;i<MAX_PATHS;i++) {
strcat(paths[i],pathsep);
strcat(paths[i],command);
printf("%s",paths[i]);
/*result = access(paths[i], F_OK);*/
printf("%d",result); }
return 0;
} /* processIt! */
processIt is the function I'm using to find the file. Any advice please?
gma@server1 [~/public_html/os/skeleton]# ./uwhich -a curl
i is 0
Errno: 2 /usr/local/jdk/bin/curl
i is 1
Errno: 2 /usr/kerberos/bin/curl
i is 2
Errno: 2 /usr/lib/courier-imap/bin/curl
i is 3
Errno: 2 /usr/local/bin/curl
i is 4
Errno: 2 /bin/curl
i is 5
/usr/bin/curl 0
/usr/bin/curl
i is 6
Errno: 2 /usr/X11R6/bin/curl
i is 7
Errno: 2 /usr/local/bin/curl
i is 8
Errno: 2 /usr/X11R6/bin/curl
i is 9
Segmentation fault (core dumped)
gma@server1 [~/public_html/os/skeleton]# echo $PATH
/usr/local/jdk/bin:/usr/kerberos/bin:/usr/lib/courier-imap/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:/usr/X11R6/bin:/home/enigma/bin
gma@server1 [~/public_html/os/skeleton]#
The program is working fine till the last directory and after that its giving a Segmentation Fault... I don't know why that is happening...
One weird thing is that when I try to print out the elements in the paths array, it says there are atleast 9 but when I use sizeof(paths) I get 4... What could be the reason for this?