I am writing own shell-like program and I keep getting errors on exec* function call.
Here is source code of core processes.c:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/uio.h>
#define BUFSIZE 128
#define EXIT_STR "exit"
int main(int argc, char ** argv) {
const char *prompt = "> ";
char buffer[BUFSIZE];
int bytes_read;
int status;
pid_t child_p;
while(1) {
printf("%s", prompt);
fflush(stdout);
bytes_read = read(0, buffer, BUFSIZE);
buffer[bytes_read-1] = '\0';
if(strncmp(EXIT_STR, buffer, bytes_read) == 0)
exit(0);
if((child_p = fork()) == 0) {
printf("[*] %d executing: %s\n", getpid(), buffer);
execlp(buffer, buffer);
printf("[*] %d got error on execlp\n", getpid());
exit(1);
} else {
waitpid(child_p, &status, 0);
printf("[*] child returned: %d\n", status);
}
}
}
I have also simple other.c program for testing:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv){
printf("Hello. I am %s with pid: %d\n", argv[0], getpid());
exit(0);
}
I use llvm on MacOS High Sierra for compilation:
$ llvm-gcc processes.c -o processes -Wall
$ ./processes
> other
[*] 6040 executing: other
[*] 6040 got error on execl
[*] child returned: 256
> ls
[*] 6041 executing: ls
[*] 6041 got error on execl
[*] child returned: 256
> exit
What am I missing?
execlp()with a null pointer of typechar *.buffer? Unless it is a single word command likelsorwho, it won’t work. Note that a newline would screw things up. Shells take care of newlines for you. When you write your own shell, you have to take care of them.perror()is usually more informative than is printing return codes.(char *) NULLas a whole additional argument.