Add a function to a program, and call that function from the command line in the function

Loading...

Add a function to a program, and call that function from the command line in the function

I have to add a custom function which shows currently running foreground and background processes launched by this shell. How do I define and call that function from the shell’s command line?
#include “smallsh.h” /*include file for example*/

/*program buffers and work pointers*/
static char inpbuf[MAXBUF], tokbuf[2*MAXBUF],
*ptr = inpbuf, *tok = tokbuf;

userin(p) /*print prompt and read a line*/
char *p;
{

int c, count;

/*initialization for later routines*/
ptr = inpbuf;
tok = tokbuf;

/*display prompt*/
printf(“%s “,p);

for(count = 0;;)
{
if((c = getchar()) == EOF)
return(EOF);

if(count

main()
{
while(userin(prompt) != EOF)
procline();
}

To try to call a function, Inside of runcommand, before the code for the child process, I tried to add another if statement saying if(cline == “dowork”){dowork();}, and tried putting in similar lines elsewhere, but nothing like that works.

Solutions/Answers:

Solution 1:

Since this is C, cline == "dowork" will not do what you want. You need to change that to:

if (strcmp(cline, "dowork") == 0)
{
    ...
}

If you wanted your shell to also handle “DOWORK”, “DoWork”, etc. you can replace strcmp with strcasecmp.

Update: since you have char **cline, you need to change that to:

if (strcmp(*cline, "dowork") == 0)

Also, you should be compiling with warnings – if you do that the compile will have told you you had a type mismatch here.

Solution 2:

You could maintain a list of internal commands like:

cd” “ls” and check the user input against this list, if an internal command is regonized simply call the function that implements the internal command.

EDIT: I was assuming you’re implementing a small shell like application.

References

Loading...