I'm writing a small shell to learn C. Now I want to execute custom commands but it is not working.
$ ./a.out
OS>ls
10357: executing ls
failed to execute ls
: (2: No such file or directory)
I must not use system call to execute custom command, I should use execvp and fork. But why is it now working? The entire code is
#include<sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <signal.h>
int mystrcmp(char const *, char const *);
struct command
{
char * const *argv;
};
static _Noreturn void err_syserr(char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, "(%d: %s)\n", errnum, strerror(errnum));
exit(EXIT_FAILURE);
}
/* Helper function that spawns processes */
static int spawn_proc(int in, int out, struct command *cmd)
{
pid_t pid;
if ((pid = fork()) == 0)
{
if (in != 0)
{
if (dup2(in, 0) < 0)
err_syserr("dup2() failed on stdin for %s: ", cmd->argv[0]);
;
close(in);
}
if (out != 1)
{
if (dup2(out, 1) < 0)
err_syserr("dup2() failed on stdout for %s: ", cmd->argv[0]);
close(out);
}
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd->argv[0]);
execvp(cmd->argv[0], cmd->argv);
err_syserr("failed to execute %s: ", cmd->argv[0]);
}
else if (pid < 0) {
err_syserr("fork failed: ");
}
return pid;
}
/* Helper function that forks pipes */
static void fork_pipes(int n, struct command *cmd)
{
int i;
int in = 0;
int fd[2];
for (i = 0; i < n - 1; ++i)
{
pipe(fd);
spawn_proc(in, fd[1], cmd + i);
close(fd[1]);
in = fd[0];
}
if (dup2(in, 0) < 0) {
err_syserr("dup2() failed on stdin for %s: ", cmd[i].argv[0]);
}
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd[i].argv[0]);
execvp(cmd[i].argv[0], cmd[i].argv);
err_syserr("failed to execute %s: ", cmd[i].argv[0]);
}
#define BUFFERSIZE 200
int main() {
char *args[80];
char buffer[BUFFERSIZE];
char *prompt = "OS";
char *a = ">";
char *tok;
tok = strtok (buffer," ");
while(buffer != NULL) {
bzero(buffer, BUFFERSIZE);
printf("%s%s",prompt,a);
fgets(buffer, BUFFERSIZE, stdin);
if(mystrcmp(buffer,"cd") == 0) {
tok = strchr(buffer,' ')+1; //use something more powerful
*strchr(tok, '\n')='\0';
cd(tok);
}
else if(mystrcmp(buffer,"exit") == 0) {
return 0;
}
else {
//system("ls"); //for testing the CWD/PWD
char *commandbuffer[] = { buffer, 0 };
//char *less[] = { "less", 0 };
struct command cmd[] = { {commandbuffer} };
fork_pipes(1, cmd);
printf("Spawned foreground process: %d\n", getpid());
}
}
return 0;
}
int mystrcmp(char const *p, char const *q)
{
int i = 0;
for(i = 0; q[i]; i++)
{
if(p[i] != q[i])
return -1;
}
return 0;
}
int cd(char *pth) {
char path[BUFFERSIZE];
strcpy(path,pth);
char *token;
char cwd[BUFFERSIZE];
if(pth[0] != '/')
{ // true for the dir in cwd
getcwd(cwd,sizeof(cwd));
strcat(cwd,"/");
strcat(cwd,path);
chdir(cwd);
} else { //true for dir w.r.t. /
chdir(pth);
}
printf("Spawned foreground process: %d\n", getpid());
return 0;
}
After
fgets(buffer, BUFFERSIZE, stdin);
the buffer always ends with an '\n' since you end your input with a return.
Thus if you just pass ls as a command you program gets ls\n and obviously there's no such command or binary in PATH.
To fix this you can simply do the following:
fgets(buffer, BUFFERSIZE, stdin);
if (buffer[strlen(buffer)-1] == '\n')
buffer[strlen(buffer)-1] = '\0';
....
The error is not with your use of execvp but with your use of fgets. fgets leaves the newline at the end of the line in the buffer, so ultimately you feed "ls\n" to execvp, and it rightly complains that it cannot find that command.
Since I'm guessing that you'll ultimately replace this code anyway, for the moment,
fgets(buffer, BUFFERSIZE, stdin);
strtok(buffer, "\n"); /* quick & dirty: remove newline if there. */
gets rid of the problem until you get around to doing the input parsing properly. I cannot recommend anything that uses strtok as a long-term solution, though. For the long term, you may be interested in the GNU-specific getline function, or indeed in libreadline (if putting your code under GPL is not a problem for you).
As usual, the case could be solved with strace.
Unfortunately, the code is too wrong and too long for me to write an exhaustive commentary.
meh.c:99:13: warning: implicit declaration of function 'cd' is invalid
in C99 [-Wimplicit-function-declaration]
cd(tok);
^
meh.c:80:11: warning: unused variable 'args' [-Wunused-variable]
char *args[80];
^
meh.c:132:11: warning: unused variable 'token' [-Wunused-variable]
char *token;
^
3 warnings generated.
What's up with this?
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <signal.h>
int mystrcmp(char const *, char const *);
struct command
{
char * const *argv;
};
static _Noreturn void err_syserr(char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, "(%d: %s)\n", errnum, strerror(errnum));
exit(EXIT_FAILURE);
}
Consider non-standard err func instead.
/* Helper function that spawns processes */
static int spawn_proc(int in, int out, struct command *cmd)
{
pid_t pid;
if ((pid = fork()) == 0)
{
if (in != 0)
{
if (dup2(in, 0) < 0)
err_syserr("dup2() failed on stdin for %s: ", cmd->argv[0]);
;
close(in);
}
if (out != 1)
{
if (dup2(out, 1) < 0)
err_syserr("dup2() failed on stdout for %s: ", cmd->argv[0]);
close(out);
}
If you have to check in and out fds like this, chances are you are already doing something wrong. Consider what happens if 'out' is 0. At this level just make sure your shell always has 0,1,2 open and that will deal with the issue.
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd->argv[0]);
execvp(cmd->argv[0], cmd->argv);
err_syserr("failed to execute %s: ", cmd->argv[0]);
}
else if (pid < 0) {
err_syserr("fork failed: ");
}
Shuffling around allows to put parent code early and avoid the indenation for long child case.
return pid;
}
/* Helper function that forks pipes */
static void fork_pipes(int n, struct command *cmd)
{
int i;
int in = 0;
int fd[2];
for (i = 0; i < n - 1; ++i)
{
pipe(fd);
spawn_proc(in, fd[1], cmd + i);
close(fd[1]);
in = fd[0];
}
if (dup2(in, 0) < 0) {
err_syserr("dup2() failed on stdin for %s: ", cmd[i].argv[0]);
}
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd[i].argv[0]);
If printfs with the newlinewere not sufficient, strace reveals the problem:
execve("/usr/bin/ls\n", ["ls\n"], [/* 58 vars */]) = -1 ENOENT (No such file or directory)
execvp(cmd[i].argv[0], cmd[i].argv);
You do realise this overwrites your shell?
err_syserr("failed to execute %s: ", cmd[i].argv[0]);
}
#define BUFFERSIZE 200
int main() {
char *args[80];
char buffer[BUFFERSIZE];
char *prompt = "OS";
char *a = ">";
char *tok;
tok = strtok (buffer," ");
while(buffer != NULL) {
bzero(buffer, BUFFERSIZE);
printf("%s%s",prompt,a);
fgets(buffer, BUFFERSIZE, stdin);
if(mystrcmp(buffer,"cd") == 0) {
tok = strchr(buffer,' ')+1; //use something more powerful
*strchr(tok, '\n')='\0';
cd(tok);
}
else if(mystrcmp(buffer,"exit") == 0) {
return 0;
}
else {
//system("ls"); //for testing the CWD/PWD
char *commandbuffer[] = { buffer, 0 };
//char *less[] = { "less", 0 };
struct command cmd[] = { {commandbuffer} };
fork_pipes(1, cmd);
printf("Spawned foreground process: %d\n", getpid());
}
}
return 0;
}
int mystrcmp(char const *p, char const *q)
{
int i = 0;
What's up with this initialisation?
for(i = 0; q[i]; i++)
Incorrect. You assume q is not longer than p.
{
if(p[i] != q[i])
return -1;
}
There are better ways than char-by-char comparison.
return 0;
}
What is this for anyway?
int cd(char *pth) {
char path[BUFFERSIZE];
strcpy(path,pth);
path and pth? Man. Consider 'orig_path' or something. Variations of one /word/ look like a typo and in fact you can easily mistype it by accident. fscking avoid.
char *token;
char cwd[BUFFERSIZE];
if(pth[0] != '/')
{ // true for the dir in cwd
getcwd(cwd,sizeof(cwd));
strcat(cwd,"/");
strcat(cwd,path);
chdir(cwd);
This is incorrect even while ignoring usual buffer overflow problems and missing error checking. If directory tree relevant to this process is modified after you getcwd, you enter the wrong directory (that's assuming chdir succeeds). What's more, paths including '..' are sensitive to symlinks.1
} else { //true for dir w.r.t. /
chdir(pth);
}
printf("Spawned foreground process: %d\n", getpid());
Seems like a copy-pasto?
return 0;
}
Related
So I am trying to read from standard input and then get the input ready so that later on it can be used inside execvp().
What I am implementing here is basically a pipe for some terminal commands.
Here is how an example of my code goes.
input:
ls -s1
sort -n
output:
commands[0]="ls"
commands[1]="-s1"
commands2[0]="��""
commands2[1]="��""
sort: cannot read: t: No such file or directory
Here is my code
# include <stdlib.h>
# include <stdio.h>
# include <unistd.h>
# include <string.h>
# include <sys/wait.h>
# define BUF_SIZE 256
int main()
{
char buffer[BUF_SIZE];
char *commands[5];
char *commands2[5];
int argc = 0;
int argc2 = 0;
fgets(buffer, BUF_SIZE, stdin);
for ( commands[argc] = strtok(buffer, " \t\n");
commands[argc] != NULL;
commands[++argc] = strtok(NULL, " \t\n") ) {
printf("commands[%d]=\"%s\"\n", argc, commands[argc]);
}
commands[argc] = NULL;
fgets(buffer, BUF_SIZE, stdin);
for ( commands2[argc2] = strtok(buffer, " \t\n");
commands2[argc2] != NULL;
commands2[++argc2] = strtok(NULL, " \t\n") ) {
printf("commands2[%d]=\"%s\"\n", argc2, commands2[argc]);
}
commands2[argc2] = NULL;
int my_pipe[2];
if (pipe(my_pipe) == -1)
{
perror("cannot create pipe\n");
}
pid_t my_pid;
my_pid = fork();
if (my_pid < 0)
{
perror("Failed fork\n");
}
if (my_pid > 0)
{
close(my_pipe[1]);
dup2(my_pipe[0], 0);
close(my_pipe[0]);
wait(NULL);
execvp(commands2[0],commands2);
}
else
{
close(my_pipe[0]);
dup2(my_pipe[1], 1);
close(my_pipe[1]);
execvp(commands[0],commands);
}
}
One major problem is that you read the second line over the first in buffer, and the commands[] array contains pointers into buffer too. That's not a recipe for happiness. The simplest fix is to define char buffer2[BUF_SIZE]; and use that in the second fgets() call and for loop.
Using argc in printf("commands2[%d]=\"%s\"\n", argc2, commands2[argc]); is a copy'n'paste bug — it should reference argc2 twice. This helped hide the previous problem.
Note that perror() does not exit; your code blunders on if pipe() fails, or if fork() fails.
The wait() in if (my_pid > 0) is bad; remove it.
If execvp() fails, you should report an error and exit with a non-zero status.
Putting those changes together yields code such as:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#define BUF_SIZE 256
int main(void)
{
char buffer[BUF_SIZE];
char buffer2[BUF_SIZE];
char *commands[5];
char *commands2[5];
int argc = 0;
int argc2 = 0;
fgets(buffer, BUF_SIZE, stdin);
for (commands[argc] = strtok(buffer, " \t\n");
commands[argc] != NULL;
commands[++argc] = strtok(NULL, " \t\n"))
{
printf("commands[%d]=\"%s\"\n", argc, commands[argc]);
}
commands[argc] = NULL;
fgets(buffer2, BUF_SIZE, stdin);
for (commands2[argc2] = strtok(buffer2, " \t\n");
commands2[argc2] != NULL;
commands2[++argc2] = strtok(NULL, " \t\n"))
{
printf("commands2[%d]=\"%s\"\n", argc2, commands2[argc2]);
}
commands2[argc2] = NULL;
int my_pipe[2];
if (pipe(my_pipe) == -1)
{
perror("cannot create pipe\n");
exit(EXIT_FAILURE);
}
pid_t my_pid = fork();
if (my_pid < 0)
{
perror("Failed fork\n");
exit(EXIT_FAILURE);
}
if (my_pid > 0)
{
close(my_pipe[1]);
dup2(my_pipe[0], 0);
close(my_pipe[0]);
execvp(commands2[0], commands2);
perror(commands2[0]);
exit(EXIT_FAILURE);
}
else
{
close(my_pipe[0]);
dup2(my_pipe[1], 1);
close(my_pipe[1]);
execvp(commands[0], commands);
perror(commands[0]);
exit(EXIT_FAILURE);
}
return EXIT_FAILURE;
}
When I run the program, it produces the appropriate output. Note that the return at the end of main() is actually never reached.
So I'm trying to create a custom shell for my school project. My method was to create child process, and have that process execute the command using the execvp() function that my professor briefly mentioned in class that we are meant to use. Here's my code, as always, any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#define MAX_LINE 80
int main(int argc, char *argv[])
{
char *input = (char*)malloc(MAX_LINE*sizeof(char));
int should_run = 1;
while(should_run){
printf("osh>");
fflush(stdout);
pid_t pid;
pid = fork();
if(pid < 0){
printf("error with creating chiled process");
return 0;
}
if(pid == 0){
fgets(input, MAX_LINE, stdin);
char *token = strtok(input," ");
if(execvp(token[0], token) < 0){
printf("Error in execution.");
return(0);
}
//should_run = 0;
}
waitpid(pid, 1, 0);
}
return 0;
}
The prototype of execvp is
int execvp(const char *file, char *const argv[]);
It expects a pointer to char as the first argument, and a NULL-terminated
pointer to an array of char*. You are passing completely wrong arguments.
You are passing a single char as first argument and a char* as the second.
Use execlp instead:
int execlp(const char *file, const char *arg, ...
/* (char *) NULL */);
So
char *token = strtok(input," \n");
if(token == NULL)
{
fprintf(stderr, "only delimiters in line\n");
exit(1);
}
if(execlp(token, token, NULL) < 0){
fprintf(stderr, "Error in execution: %s\n", strerror(errno));
exit(1);
}
Also the convention in UNIX is to print error messages to stderr and a process with an error should
have an exit status other than 0.
As Pablo's states, you are passing the wrong arguments to execvp().
You can consider coding by yourself a function (char **strsplit(char *str, char delim)) which takes a string and split it into smaller pieces, returning an array of strings.
Also don't ignore compiler's warnings, they tell you a lot of things, and I suggest you to compile with gcc -Wall -Wextra -Werror to get almost any possible error in your program.
I tell you this because waitpid() takes as second argument a pointer to integer, to get an update of the status of the forked program. With this status you how the program exited (normally, segf, bus error...), you can use it to print an error if something went wrong.
You can consider using execv() instead (I know I'm going off topic, but you can learn useful things doing this), and find by yourself the correct executable(s).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#define MAX_LINE 255
char **strsplit(char *str, char delim);
char *strjoin(char const *s1, char const *s2);
int isexec(char *path)
{
struct stat buf;
lstat(path, &buf);
if (S_ISREG(buf.st_mode) && (S_IXUSR & buf.st_mode))
return (1);
return (0);
}
static char *find_exec_readdir(char *paths, char *cmd)
{
DIR *dir;
struct dirent *dirent;
char *exec;
exec = NULL;
if ((dir = opendir(paths)) != NULL)
{
while ((dirent = readdir(dir)) != NULL)
{
if (!strcmp(dirent->d_name, cmd))
{
exec = strdup(dirent->d_name);
break ;
}
}
if (closedir(dir))
dprintf(2, "Failed closing dir.\n");
}
return (exec);
}
char *find_exec(char *cmd, char **paths)
{
char *exec;
char *path;
char *tmp;
int i;
i = -1;
exec = NULL;
path = NULL;
if ((cmd[0] == '.' || cmd[0] == '/'))
{
if (isexec(cmd))
return (strdup(cmd));
return (NULL);
}
while (paths[++i])
if ((exec = find_exec_readdir(paths[i], cmd)) != NULL)
{
tmp = strjoin(paths[i], "/");
path = strjoin(tmp, exec);
free(tmp);
free(exec);
break ;
}
return (path);
}
int handle_return_status(int status)
{
int sig;
int i;
if (!WIFEXITED(status) && WIFSIGNALED(status))
{
sig = WTERMSIG(status);
i = -1;
while (++i <= 13)
{
if (print_signal_error(sig))
{
return (-1);
}
}
dprintf(2, "Process terminated with unknown signal: %d\n", sig, NULL);
return (-1);
}
return (0);
}
int main(int argc, char *argv[])
{
char *input = NULL;
char **command = NULL;
int should_run = 1;
int status = 0;
(void)argc;
(void)argv;
if ((input = (char*)malloc(MAX_LINE*sizeof(char))) == NULL)
return (dprintf(2, "Failed to malloc, abort.\n"));
while(should_run){
printf("osh> ");
fflush(stdout);
pid_t pid;
pid = fork();
if(pid < 0)
return (dprintf(2, "error with creating chiled process\n"));
if(pid == 0){
fgets(input, MAX_LINE, stdin);
command = strsplit(input, ' ');
command[0] = find_exec(command[0], strsplit(getenv("PATH"), ':'));
if(execv(command[0], &command[1]) < 0)
return (dprintf(2, "Error in execution.\n"));
//should_run = 0;
}
waitpid(pid, &status, 0);
handle_ret_status(status);
}
return 0;
}
I'm writing a small shell in C as an exercis to learn about linux and C. Now I can execute custom commands and the exit command, but I can't execute a builtin CD command since I don't know how to split it in two part (the cd command and the name of the directory to CD to).
The desired functionality is that my program should accept the cd command with a parameter that is the directory. I can do it with command-line arguments but I don't know how to do it in its current form. How can it be done?
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUFFER_LEN 1024
#define BUFFERSIZE 1024
int mystrcmp(char const *, char const *);
void err_syserr(char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, "(%d: %s)\n", errnum, strerror(errnum));
exit(EXIT_FAILURE);
}
int main() {
char line[BUFFER_LEN];
char* argv[100];
char* path= "/bin/";
char progpath[20];
int argc;
size_t length;
char *token;
int i=0;
int pid;
while(1) {
i = 0;
printf("miniShell>> ");
if(!fgets(line, BUFFER_LEN, stdin)) {
break;
}
length = strlen(line);
if (line[length - 1] == '\n') {
line[length - 1] = '\0';
}
if(strcmp(line, "exit")==0) {
break;
}
if(strcmp(line, "cd")==0) {
/*printf("change directory to %s\n", argv[2]);
chdir(argv[2]);*/
}
token = strtok(line," ");
while(token!=NULL) {
argv[i]=token;
token = strtok(NULL," ");
i++;
}
argv[i]=NULL;
argc=i;
for(i=0; i<argc; i++) {
printf("%s\n", argv[i]);
}
strcpy(progpath, path);
strcat(progpath, argv[0]);
for(i=0; i<strlen(progpath); i++) {
if(progpath[i]=='\n') {
progpath[i]='\0';
}
}
pid= fork();
if(pid==0) {
execvp(progpath,argv);
fprintf(stderr, "Child process could not do execvp\n");
} else {
wait(NULL);
printf("Child exited\n");
}
}
return (0);
}
int mystrcmp(char const *p, char const *q)
{
int i = 0;
for(i = 0; q[i]; i++)
{
if(p[i] != q[i])
return -1;
}
return 0;
}
int cd(char *pth) {
char path[BUFFERSIZE];
char cwd[BUFFERSIZE];
char * return_value;
int other_return;
strcpy(path,pth);
if(pth[0] != '/')
{
return_value = getcwd(cwd,sizeof(cwd));
strcat(cwd,"/");
strcat(cwd,path);
other_return = chdir(cwd);
} else {
other_return = chdir(pth);
}
printf("Spawned foreground process: %d\n", getpid());
return 0;
}
Use strpbrk or strsep to split your input into white-space separated tokens, then use strcmp on the first one and use the remaining ones as arguments.
This answer to a related question has an example, and here are some notes on portability.
I'd suggest to parse your argument with the getopt function from unistd library. It's covered in this question too.
Here is the documentation for getopt command.
/tmp/ccpGLxUa.o: In function `Janitor':
digenv2.c:(.text+0x656): undefined reference to `WIFEEXITED'
collect2: error: ld returned 1 exit status
I'm trying to compile a file that worked before. Now I get thi error message when compiling. The full program is
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
pid_t foreground = -1;
struct command
{
char * const *argv;
};
static _Noreturn void err_syserr(char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, "(%d: %s)\n", errnum, strerror(errnum));
exit(EXIT_FAILURE);
}
/* Helper function that spawns processes */
static int spawn_proc(int in, int out, struct command *cmd)
{
pid_t pid;
if ((pid = fork()) == 0)
{
if (in != 0)
{
if (dup2(in, 0) < 0)
err_syserr("dup2() failed on stdin for %s: ", cmd->argv[0]);
;
close(in);
}
if (out != 1)
{
if (dup2(out, 1) < 0)
err_syserr("dup2() failed on stdout for %s: ", cmd->argv[0]);
close(out);
}
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd->argv[0]);
execvp(cmd->argv[0], cmd->argv);
err_syserr("failed to execute %s: ", cmd->argv[0]);
}
else if (pid < 0)
err_syserr("fork failed: ");
return pid;
}
/* Helper function that forks pipes */
static void fork_pipes(int n, struct command *cmd)
{
int i;
int in = 0;
int fd[2];
for (i = 0; i < n - 1; ++i)
{
pipe(fd);
spawn_proc(in, fd[1], cmd + i);
close(fd[1]);
in = fd[0];
}
if (dup2(in, 0) < 0)
err_syserr("dup2() failed on stdin for %s: ", cmd[i].argv[0]);
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd[i].argv[0]);
execvp(cmd[i].argv[0], cmd[i].argv);
err_syserr("failed to execute %s: ", cmd[i].argv[0]);
}
int main(int argc, char **argv)
{
int i;
if (argc == 1) /* There were no arguments */
{
char *printenv[] = { "printenv", 0};
char *sort[] = { "sort", 0 };
char *less[] = { "less", 0 };
struct command cmd[] = { {printenv}, {sort}, {less} };
fork_pipes(3, cmd);
}
else
{
if (strcmp(argv[1], "cd") == 0) /* change directory */
{
printf("change directory to %s\n", argv[2]);
chdir(argv[2]);
}
else if (strcmp(argv[1], "exit") == 0)
{
printf("exit\n");
exit(0);
}
else
{
char *tmp;
int len = 1;
for (i = 1; i < argc; i++)
{
len += strlen(argv[i]) + 2;
}
tmp = (char *) malloc(len);
tmp[0] = '\0';
int pos = 0;
for (i = 1; i < argc; i++)
{
pos += sprintf(tmp + pos, "%s%s", (i == 1 ? "" : "|"), argv[i]);
}
char *printenv[] = { "printenv", 0};
char *grep[] = { "grep", "-E", tmp, NULL};
char *sort[] = { "sort", 0 };
char *less[] = { "less", 0 };
struct command cmd[] = { {printenv}, {grep}, {sort}, {less} };
fork_pipes(4, cmd);
free(tmp);
}
}
return(0);
}
/*Remove zoombie processes*/
/*Return if background process terminated*/
/*
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
*/
void Janitor(int signal) {
if(signal==SIGCHLD) { /*Child process terminated, stopped, or continued*/
int a = 1;
while(a) {
pid_t pid_my1 = waitpid(-1, &signal, WNOHANG);
/*WNOHANG = return immediately if no child has exited*/
/*http://linux.die.net/man/2/waitpid*/
if(0<pid_my1) { /*Still things to clean up*/
if(pid_my1!=foreground) { /*Don't stop me since it's the foregound process*/
/*http://linux.die.net/man/3/wait*/
if(WIFEEXITED(signal)) { /*Child process terminated*/
/*FIXME*/
}
}
}
else { /*All work done, for now*/
a = 0;
}
}
}
}
The program was compiling fine just a few days ago. It is in a github repository. I compiled, added, commit and pushed and then when I check it out I get the above error message when compiling. Why?
You haven't included the necessary headers for wait(2) options:
#include <sys/types.h>
#include <sys/wait.h>
I asked about my code and the answer was that it is incorrect.
perror usage in this case
Now I wonder how I can adjust and improve so that I no longer will have these errors?
execvp does not return, except if an error occurs, so if all works,
the enclosing function will never return.
the value 'i' is already past the end of the array in 'cmd' due to the
prior loop, so 'cmd[i].argv[0] is not correct.
cmd is not an array, of struct command, so should not be indexed
the first entry in cmd.argv is a pointer to an array where the last
entry is NULL. the execvp will work on that (and only that) array so
all other pointers to arrays will be ignored
There are a large number of errors in the code. for instance, the
first time through the loop in fork_pipe() 'in' contains garbage. the
second parameter passed to execvp() needs to be a pointer to character
strings, with a final NULL pointer. That final NULL pointer is
missing, There are plenty more problems
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
struct command
{
const char **argv;
};
/* Helper function that spawns processes */
int spawn_proc (int in, int out, struct command *cmd) {
pid_t pid;
if ((pid = fork ()) == 0) {
if (in != 0) {
/*if (dup2(in, 0) == -1) {
perror("dup2 failed");
exit(1);
}*/
dup2 (in, 0);
close (in);
}
if (out != 1) {
dup2 (out, 1);
close (out);
}
if (execvp(cmd->argv [0], (char * const *)cmd->argv) < 0) {
perror("execvp failed");
exit(1);
}
} else if (pid < 0) {
perror("fork failed");
exit(1);
}
return pid;
}
/* Helper function that forks pipes */
int fork_pipes (int n, struct command *cmd) {
int i;
int in, fd [2];
for (i = 0; i < n - 1; ++i) {
pipe (fd);
spawn_proc (in, fd [1], cmd + i);
close (fd [1]);
in = fd [0];
}
dup2 (in, 0);
/*return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);*/
if (execvp (cmd [i].argv [0], (char * const *)cmd [i].argv) < 0) {
perror("execvp failed");
exit(1);
} else {
return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}
}
int main (int argc, char ** argv) {
int i;
if (argc == 1) { /* There were no arguments */
const char *printenv[] = { "printenv", 0};
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {sort}, {less} };
return fork_pipes (3, cmd);
}
if (argc > 1) { /* I'd like an argument */
if (strncmp(argv[1], "cd", 2) && strncmp(argv[1], "exit", 2)) {
char *tmp;
int len = 1;
for( i=1; i<argc; i++)
{
len += strlen(argv[i]) + 2;
}
tmp = (char*) malloc(len);
tmp[0] = '\0';
int pos = 0;
for( i=1; i<argc; i++)
{
pos += sprintf(tmp+pos, "%s%s", (i==1?"":"|"), argv[i]);
}
const char *printenv[] = { "printenv", 0};
const char *grep[] = { "grep", "-E", tmp, NULL};
const char *sort[] = { "sort", 0 };
const char *less[] = { "less", 0 };
struct command cmd [] = { {printenv}, {grep}, {sort}, {less} };
return fork_pipes (4, cmd);
free(tmp);
} else if (! strncmp(argv[1], "cd", 2)) { /* change directory */
printf("change directory to %s\n" , argv[2]);
chdir(argv[2]);
} else if (! strncmp(argv[1], "exit", 2)) { /* change directory */
printf("exit\n");
exit(0);
}
}
exit(0);
}
Transferring comments into (part of) an answer.
You don't need the test on execvp() (if it returns, it failed), but you do need the error reporting and exit call after it.
The 'cmd is not an array' comment seems to be bogus; inside fork_pipes(), it is an array. It is not used as an array inside spawn_proc().
I think the comment 'The first entry in cmd.argv is a pointer to an array where the last entry is NULL. The execvp will work on that (and only that) array so all other pointers to arrays will be ignored' is bogus too. I think they overlooked that you're creating an array of struct command's.
I think the comment 'the value i is already past the end of the array in cmd due to the prior loop, so cmd[i].argv[0] is not correct' is incorrect because the loop is for (i = 0; i < n - 1; i++) so i is n-1 after the loop, and the array cmd has elements 0..n-1 to address.
However, the value of in in the first call to spawn_proc() is indeed garbage. Probably you can simply set it to 0 (STDIN_FILENO) and be OK, but you need to verify that. But the comment about the second argument to execvp() is peculiar — the cast should be absent, but otherwise the code looks OK to me. I should add that I've not yet run a compiler over any of this, so anything I've said so far stands to be corrected by a compiler. But I'm not doing the analysis casually either… Are you compiling with your compiler set fussy: gcc -Wall -Wextra -Werror as a minimum (I use more options!)?
In fork_pipes(), the if test on execvp() and the else clause are weird. You just need calls to execvp(), perror() and exit().
These comments above stand basically accurate. Here is some modified code, but the modifications are mostly cosmetic. The err_syserr() function is based on what I use for reporting errors. It is a varargs function that also reports the system error. It is better than perror() because (a) it can format more comprehensively and (b) it exits.
I was getting compilation warnings like:
ft13.c: In function ‘spawn_proc’:
ft13.c:45:9: error: passing argument 2 of ‘execvp’ from incompatible pointer type [-Werror]
execvp(cmd->argv[0], cmd->argv);
^
In file included from ft13.c:6:0:
/usr/include/unistd.h:440:6: note: expected ‘char * const*’ but argument is of type ‘const char **’
int execvp(const char *, char * const *);
The easiest way to fix these is to place the const in the correct place in struct command and to remove the const from the argument lists for the various commands.
Other changes are more cosmetic than really substantive (the uninitialized in was the only serious bug to fix). I've use my error reporting code, and checked some extra system calls (the dup2() ones, for example), and cleaned up the execvp() and error reporting. I moved the tests for exit and cd ahead of the general code to avoid repeating the tests. Also, you were using strncmp() and the test for exit was only looking at ex, but ex is a system command… Use strcmp(). I use strcmp(x, y) == 0 in the condition; the relational operator in use mimics the relational operation I'm testing (so strcmp(x, y) >= 0 tests for x greater than or equal to y, etc.).
Modern POSIX does not require #include <sys/types.h> as an include. The other headers include it as necessary.
Source: ft13.c
Compiled to ft13.
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct command
{
char * const *argv;
};
static _Noreturn void err_syserr(char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, "(%d: %s)\n", errnum, strerror(errnum));
exit(EXIT_FAILURE);
}
/* Helper function that spawns processes */
static int spawn_proc(int in, int out, struct command *cmd)
{
pid_t pid;
if ((pid = fork()) == 0)
{
if (in != 0)
{
if (dup2(in, 0) < 0)
err_syserr("dup2() failed on stdin for %s: ", cmd->argv[0]);
close(in);
}
if (out != 1)
{
if (dup2(out, 1) < 0)
err_syserr("dup2() failed on stdout for %s: ", cmd->argv[0]);
close(out);
}
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd->argv[0]);
execvp(cmd->argv[0], cmd->argv);
err_syserr("failed to execute %s: ", cmd->argv[0]);
}
else if (pid < 0)
err_syserr("fork failed: ");
return pid;
}
/* Helper function that forks pipes */
static void fork_pipes(int n, struct command *cmd)
{
int i;
int in = 0;
int fd[2];
for (i = 0; i < n - 1; ++i)
{
pipe(fd);
spawn_proc(in, fd[1], cmd + i);
close(fd[1]);
in = fd[0];
}
if (dup2(in, 0) < 0)
err_syserr("dup2() failed on stdin for %s: ", cmd[i].argv[0]);
fprintf(stderr, "%d: executing %s\n", (int)getpid(), cmd[i].argv[0]);
execvp(cmd[i].argv[0], cmd[i].argv);
err_syserr("failed to execute %s: ", cmd[i].argv[0]);
}
int main(int argc, char **argv)
{
int i;
if (argc == 1) /* There were no arguments */
{
char *printenv[] = { "printenv", 0};
char *sort[] = { "sort", 0 };
char *less[] = { "less", 0 };
struct command cmd[] = { {printenv}, {sort}, {less} };
fork_pipes(3, cmd);
}
else
{
if (strcmp(argv[1], "cd") == 0) /* change directory */
{
printf("change directory to %s\n", argv[2]);
chdir(argv[2]);
}
else if (strcmp(argv[1], "exit") == 0)
{
printf("exit\n");
exit(0);
}
else
{
char *tmp;
int len = 1;
for (i = 1; i < argc; i++)
{
len += strlen(argv[i]) + 2;
}
tmp = (char *) malloc(len);
tmp[0] = '\0';
int pos = 0;
for (i = 1; i < argc; i++)
{
pos += sprintf(tmp + pos, "%s%s", (i == 1 ? "" : "|"), argv[i]);
}
char *printenv[] = { "printenv", 0};
char *grep[] = { "grep", "-E", tmp, NULL};
char *sort[] = { "sort", 0 };
char *less[] = { "less", 0 };
struct command cmd[] = { {printenv}, {grep}, {sort}, {less} };
fork_pipes(4, cmd);
free(tmp);
}
}
return(0);
}
Example runs
Sample 1:
$ ./ft13 | cat
1733: executing less
1735: executing printenv
1736: executing sort
Apple_PubSub_Socket_Render=/private/tmp/com.apple.launchd.sl7NmyZPgI/Render
BASH_ENV=/Users/jleffler/.bashrc
CDPATH=:/Users/jleffler:/Users/jleffler/src:/Users/jleffler/src/perl:/Users/jleffler/src/sqltools:/Users/jleffler/lib:/Users/jleffler/doc:/Users/jleffler/work:/Users/jleffler/ids
CLICOLOR=1
…lots of environment omitted…
VISUAL=vim
XPC_FLAGS=0x0
XPC_SERVICE_NAME=0
_=./ft13
__CF_USER_TEXT_ENCODING=0x1F7:0x0:0x0
$
Sample 2:
$ ./ft13 PATH | cat
1739: executing printenv
1737: executing less
1740: executing grep
1741: executing sort
CDPATH=:/Users/jleffler:/Users/jleffler/src:/Users/jleffler/src/perl:/Users/jleffler/src/sqltools:/Users/jleffler/lib:/Users/jleffler/doc:/Users/jleffler/work:/Users/jleffler/ids
DYLD_LIBRARY_PATH=/usr/lib:/usr/informix/11.70.FC6/lib:/usr/informix/11.70.FC6/lib/esql:/usr/informix/11.70.FC6/lib/cli
GOPATH=/Users/jleffler/Software/go-1.2
LD_LIBRARY_PATH=/usr/lib:/usr/gnu/lib:/usr/gcc/v4.9.1/lib
MANPATH=/Users/jleffler/man:/Users/jleffler/share/man:/usr/local/mysql/man:/usr/gcc/v4.9.1/share/man:/Users/jleffler/perl/v5.20.1/man:/usr/local/man:/usr/local/share/man:/opt/local/man:/opt/local/share/man:/usr/share/man:/usr/gnu/man:/usr/gnu/share/man
PATH=/Users/jleffler/bin:/usr/informix/11.70.FC6/bin:.:/usr/local/mysql/bin:/usr/gcc/v4.9.1/bin:/Users/jleffler/perl/v5.20.1/bin:/usr/local/go/bin:/Users/jleffler/Software/go-1.2/bin:/usr/local/bin:/opt/local/bin:/usr/bin:/bin:/usr/gnu/bin:/usr/sbin:/sbin
$