I am trying to make use of execvp()
to execute child processes but it gives me following error and I am unable to fix it can someone point me in direction what I am doing wrong?
My code:
#include "apue.h"
#include <sys/wait.h>
static void sig_int(int); /* our signal-catching function */
int
main(void)
{
char buf[MAXLINE]; /* from apue.h */
pid_t pid;
int status;
if (signal(SIGINT, sig_int) == SIG_ERR)
err_sys("signal error");
printf("%% "); /* print prompt (printf requires %% to print %) */
while (fgets(buf, MAXLINE, stdin) != NULL) {
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = 0; /* replace newline with null */
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* child */
execlp(buf, buf); //this line is where I am not sure if I am wrong.
err_ret("couldn't execute: %s", buf);
exit(127);
}
/* parent */
if ((pid = waitpid(pid, &status, 0)) < 0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}
void
sig_int(int signo)
{
printf("interrupt\n%% ");
}
My warming/error:
shell2.c: In function ‘main’:
shell2.c:24:16: warning: passing argument 2 of ‘execvp’ from incompatible pointer type [-Wincompatible-pointer-types]
execvp(buf, buf);
^~~
In file included from ../csci3800sp22/apue.3e/include/apue.h:26:0,
from shell2.c:1:
/usr/include/unistd.h:578:12: note: expected ‘char * const*’ but argument is of type ‘char *’
extern int execvp (const char *__file, char *const __argv[])
Expected result: When I run other command (execlp) it gives me following result :
[singhrav@csci-gnode-02 ~/lab1]$ ls
Makefile shell2 shell2.c
[singhrav@csci-gnode-02 ~/lab1]$ ./shell2
% ls
Makefile shell2 shell2.c
% ps
PID TTY TIME CMD
24839 pts/1 00:00:00 tcsh
25175 pts/1 00:00:00 shell2
25204 pts/1 00:00:00 ps
% ls -l
couldn't execute: ls -l: No such file or directory
Problem with execlp()
is it does not execute ls -l
, I wanted to be able to use ls
, ps
& ls -l
so that's why I decided to use execvp()
but when I use execvp()
and run my ./shell2
command it gives me following error:
[singhrav@csci-gnode-02 ~/lab1]$ ./shell2
% ls
couldn't execute: ls: Bad address
% ps
couldn't execute: ps: Bad address
% ls -l