master
Alessandro Mauri 3 years ago
parent 1169a52115
commit 7414651893
  1. 3
      config.h
  2. 23
      fstr.c
  3. 14
      fstr.h
  4. 8
      makefile
  5. 55
      msh.c

@ -4,5 +4,6 @@
#define DEF_HISTSIZE 512
#define DEF_HISTPATH ".history"
#define DEF_SHELLRC ".mshrc"
#define DEF_CHUNKSIZE 256
#endif
#endif

@ -0,0 +1,23 @@
#define _POSIX_C_SOURCE 200809l
#include <stdlib.h>
#include "fstr.h"
#include "config.h"
void fstr_add_space(fstr_t *fs)
{
erealloc(fs->s, fs->len + fs->space + DEF_CHUNKSIZE + 1);
fs->space += DEF_CHUNKSIZE;
}
void fstr_append_char(fstr_t *fs, char c)
{
if (!fs)
return;
if (fs->space < 1)
fstr_add_space(fs);
fs->s[fs->len++] = c;
fs->s[fs->len] = '\0';
fs->space--;
}

@ -0,0 +1,14 @@
#ifndef _MSH_FSTR_H
#define _MSH_FSTR_H
// current length of the string and remaining space, total allocated space is
// len + space
typedef struct _fstr {
unsigned long int len;
unsigned long int space;
char *s;
} fstr_t;
void fstr_append_char(fstr_t *, char);
#endif

@ -0,0 +1,8 @@
.POSIX:
CFLAGS = -Wall -Werror -pedantic -Wextra -std=c11
msh: msh.c fstr.c
clean:
rm -f msh *.o

55
msh.c

@ -1,7 +1,16 @@
#define _POSIX_C_SOURCE 200809l
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h>
char *PS1 = NULL;
#include "config.h"
#include "fstr.h"
fstr_t PS1 = {0};
unsigned int histsize = DEF_HISTSIZE;
// Buffered user data
@ -10,19 +19,29 @@ struct {
char *home;
uid_t uid;
gid_t gid;
} uinfo;
} uinfo = {0};
struct {
// $ or #
char tag;
} shinfo;
void sh_fill_uinfo(void);
void sh_update_uinfo(void);
void sh_update_shinfo(void);
void sh_update_ps1(void);
inline void sh_print_ps1(void);
int main(int argc, char **argv)
{
sh_fill_uinfo();
(void)argc;
(void)argv;
for (;;) {
sh_update_uinfo();
sh_update_shinfo();
sh_update_ps1();
sh_print_ps1();
for(;;);
}
return EXIT_SUCCESS;
@ -30,19 +49,33 @@ int main(int argc, char **argv)
void sh_fill_uinfo(void)
{
struct pwuid pw;
uinfo.uid = getuid();
uidfo.gid = getgid();
struct passwd *pw;
uid_t nuid;
nuid = getuid();
if (nuid == uinfo.uid && uinfo.name)
return;
uinfo.uid = nuid;
pw = getpwuid(uinfo.uid);
// User not found
if (!pw)
exit(EXIT_FAILURE);
uinfo.gid = pw->pw_gid;
uinfo.name = estrdup(pw->pw_name);
uinfo.home = estrdup(pw->pw_dir);
}
void sh_update_shinfo(void)
{
shinfo.tag = uinfo.uid ? '$' : '#';
}
inline void sh_print_ps1(void)
{
puts(PS1);
putchar(' ');
puts(PS1.s);
}
void sh_update_ps1(void)
{
}
fstr_append_char(&PS1, shinfo.tag);
fstr_append_char(&PS1, ' ');
}