Ok I found where the seg-fault is happening, but I dont know why it happens.
Code:
char * env;
env = "/usr/local/bin:/bin:/usr/bin";
...
int tryEnv(char * theFileName)
{
char * myEnv;
myEnv = strtok(env, ":");
char * myFile;
while (1)
{
/* check if there is nothing else to extract */
if(myEnv == NULL)
{
printf("DONE\n");
break;
}
/* extract string from string sequence */
strcpy(myFile, myEnv);
strcat(myFile, "/");
strcat(myFile, theFileName);
int result;
result = access (myFile, X_OK);// TODO This causes Seg-Fault
/* print string after tokenized, check if exists */
//if(access(myFile,X_OK)) // This i will use once the above works
//{
printf("%s\n", myFile);
//}
/* Finally get the next Env (if the othe failed) */
myEnv = strtok(NULL, ":");
}
return 0;
}
main(int argc, char **argv)
{
char *fileName;
fileName = fgets (line, BUFFER_LENGTH, stdin); // i type the file name "ls"
ret = tryEnv(fileName);
..
}
The above cause a segfault (I show at the "TODO" comment). But i think i am calling the system call "access" correctly, because it works in this program:
Code:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main()
{
int result;
char *filename1 = "/bin/ls";
char *filename2 = "/usr/kerberos/bin/ls";
char *filename3 = "/usr/local/bin/ls";
result = access (filename1, X_OK); // works, returns 0
printf("%d\n",result);
result = access (filename2, X_OK); // works, returns -1
printf("%d\n",result);
result = access (filename3, X_OK); // works, returns -1
printf("%d\n",result);
}