My knowledge of C is very limited. I'm trying to tokenize a String passed to a server from a client, because I want to use passed arguments toexecve
. The arguments passed viabuffer
needs to be copied to*argv
and tokenized such thatbuffer
's tokens can be accessed withargv[0]
, argv[1]
, etc. Obviously I'm doing something incorrectly.
n = read(sockfd, buffer, sizeof(buffer));
strcpy(*argv, buffer);
printf("buffer:%s\n", buffer);
printf("argv:%s\n", *argv);
printf("argv[0]:%s\n", argv[0]);
printf("argv[1]:%s\n", argv[1]);
*argv = strtok_r(*argv, " ", argv);
printf("argv:%s\n", *argv);
i = fork();
if (i < 0) {
//Close socket on fork error.
perror("fork");
exit(-1);
} else if (i == 0) {
//execve on input args
execve(argv[0], &argv[0], 0);
exit(0);
} else {
wait(&status);
//close(sockfd);
}
Passing the arguments "/bin/date -u" with the above code gives an output of:
buffer:/bin/date -u
argv:/bin/date -u
argv[0]:/bin/date -u
argv[1]:(null)
What I what is an output of:
buffer:/bin/date -u
argv:/bin/date -u
argv[0]:/bin/date
argv[1]:-u
I tried usingstrtok_r()
, but it didn't work as I intended. The snippet I inserted was:
*argv = strtok_r(*argv, " ", argv);
printf("argv:%s\n", *argv);
which give an output of argv:/bin/date
.
Thanks in advanced, SO.
Edit: I don't have to explicitly tokenizebuffer
like I have above. Any way to get arguments from the client passed to the server works fine.